#graph905. 稳定婚姻
稳定婚姻
Stable Marriage
Problem Source
BZOJ 2140
Problem Description
We know the marital status of couples. Call the husband of the -th couple and the wife . If some man and some woman have ever been in a relationship (whether in university, high school, or even kindergarten, with ), then when either of them has trouble with their spouse (i.e. with , or with ), there is a possibility that they run away together. Suppose and his spouse fall out of love; then and rekindle their old flame, and in turn , feeling cuckolded, contacts his first love ... a chain of divorces unfolds like falling dominoes. If, under the premise that and divorce, these people can still end up paired into couples, then marriage 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 , the number of couples.
The next lines each contain two strings, the names of the couples (wife first, then husband), separated by a space.
The -th line contains a positive integer , the number of pairs who have ever liked each other.
The next lines each contain two strings, the names of those 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 ; each relationship appears at most once in the input; the last lines will not introduce any name not seen before; the people all have distinct names; , .
Output Format
The output contains lines; the -th line is Safe if marriage 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