#P1407. [国家集训队] 稳定婚姻

[国家集训队] 稳定婚姻

Description

We know the marital status of nn couples. Denote the man of the ii-th couple as BiB_i and the woman as GiG_i. If some man BiB_i and some woman GjG_j once dated (whether in college, high school, or even kindergarten, with iji \neq j), then when either party has problems with his or her spouse (that is, BiB_i with GiG_i or BjB_j with GjG_j), they may elope. Suppose BiB_i and his spouse GiG_i do not get along, then BiB_i and GjG_j rekindle their relationship, and then BjB_j, feeling upset after being cheated on, contacts his first love GkG_k... A chain of divorces follows like dominoes. If, under the premise that BiB_i and GiG_i divorce, these 2n2n people can still eventually be paired into nn couples, then we call marriage ii unsafe; otherwise, marriage ii is safe.

Given the required information, your task is to determine whether each marriage is safe.

Input Format

The first line contains a positive integer nn, the number of couples.

Each of the following nn lines contains two strings, the names of these nn couples (female first, then male), separated by a space.

The n+2n+2-th line contains a positive integer mm, the number of couples who once dated each other.

Each of the following mm lines contains two strings, the names of these mm couples who once dated each other (female first, then male), separated by a space.

Output Format

The output contains nn lines. The ii-th line is Safe (if marriage ii is safe) or Unsafe (if marriage ii is unsafe).

2
Melanie Ashley
Scarlett Charles
1
Scarlett Ashley
Safe
Safe
2
Melanie Ashley
Scarlett Charles
2
Scarlett Ashley
Melanie Charles
Unsafe
Unsafe

Hint

For 20%20\% of the testdata, n20n \le 20.

For 40%40\% of the testdata, n100n \le 100, m400m \le 400.

For 100%100\% of the testdata, all name strings contain only English letters, are case-sensitive, and have length no greater than 88. Each relationship appears only once in the input. The last mm lines of the input file will not contain any names that did not appear before. All 2n2n names are distinct. 1n40001 \le n \le 4000, 0m200000 \le m \le 20000.

Translated by ChatGPT 5