#graph905. 稳定婚姻

稳定婚姻

Stable Marriage

Problem Source

BZOJ 2140

Problem Description

We know the marital status of nn couples. Call the husband of the ii-th couple BiB_i and the wife GiG_i. If some man BiB_i and some woman GjG_j have ever been in a relationship (whether in university, high school, or even kindergarten, with i≤ji \le j), then when either of them has trouble with their spouse (i.e. BiB_i with GiG_i, or BjB_j with GjG_j), there is a possibility that they run away together. Suppose BiB_i and his spouse GiG_i fall out of love; then BiB_i and GjG_j rekindle their old flame, and in turn BjB_j, feeling cuckolded, contacts his first love GkG_k... a chain of divorces unfolds like falling dominoes. If, under the premise that BiB_i and GiG_i divorce, these 2n2n people can still end up paired into nn couples, then marriage ii is called unsafe; otherwise it is safe.

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

Input Format

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

The next nn lines each contain two strings, the names of the nn couples (wife first, then husband), separated by a space.

The (n+2)(n+2)-th line contains a positive integer mm, the number of pairs who have ever liked each other.

The next mm lines each contain two strings, the names of those mm pairs who have ever liked each other (wife first, then husband), separated by a space.

For all data: every name consists only of English letters (case-sensitive), with length at most 88; each relationship appears at most once in the input; the last mm lines will not introduce any name not seen before; the 2n2n people all have distinct names; 1≤n≤40001 \le n \le 4000, 0≤m≤200000 \le m \le 20000.

Output Format

The output contains nn lines; the ii-th line is Safe if marriage ii is safe, or Unsafe if it is unsafe.

Sample Input 1

2
Melanie Ashley
Scarlett Charles
1
Scarlett Ashley

Sample Output 1

Safe
Safe

Sample Input 2

2
Melanie Ashley
Scarlett Charles
2
Scarlett Ashley
Melanie Charles

Sample Output 2

Unsafe
Unsafe