题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1116
The input consists of T test cases. The number of them (T) is given on the first line of the input file. Each test case begins with a line containing a single integer number Nthat indicates the number of plates (1 <= N <= 100000). Then exactly Nlines follow, each containing a single word. Each word contains at least two and at most 1000 lowercase characters, that means only letters 'a' through 'z' will appear in the word. The same word may appear several times in the list.
Output
Your program has to determine whether it is possible to arrange all the plates in a sequence such that the first letter of each word is equal to the last letter of the previous word. All the plates from the list must be used, each exactly once. The words mentioned several times must be used that number of times.
If there exists such an ordering of plates, your program should print the sentence "Ordering is possible.". Otherwise, output the sentence "The door cannot be opened.".
Sample Input
3 2 acm ibm 3 acm malform mouse 2 ok ok
Sample Output
The door cannot be opened. Ordering is possible. The door cannot be opened.
给你n个单词,问是否能连成一起
#pragma GCC optimize(2) #include<stdio.h> #include<algorithm> #include<iostream> #include<string.h> #include<string> #include<set> #include<vector> #include<queue> using namespace std; const int maxn = 500; const int inf = 0x3f3f3f3f; typedef long long ll; int f[maxn], in[maxn], ou[maxn], vis[maxn]; int t; int find(int x) { if (x == f[x]) { return x; } else { return find(f[x]); } } int main() { //freopen("C://input.txt", "r", stdin); scanf("%d", &t); while (t--) { int n; string s; scanf("%d", &n); for (int i = 0; i < 30; i++) { f[i] = i; } int r = 0; int x, y; memset(in, 0, sizeof(in)); memset(ou, 0, sizeof(ou)); memset(vis, 0, sizeof(vis)); for (int i = 1; i <= n; i++) { cin >> s; x = s[0] - 'a'; y = s[s.length() - 1] - 'a'; in[y]++; ou[x]++; f[x] = f[y] = find(x); vis[x] = vis[y] = 1; } for (int i = 0; i <= 30; i++) { if (vis[i] && i == f[i]) { r++; } } if (r > 1) { cout << "The door cannot be opened." << endl; continue; } x = 0, y = 0; int z = 0; bool flag = false; for (int i = 0; i < 30; i++) { if (vis[i] && in[i] != ou[i]) { if (in[i] == ou[i] + 1) { x++; } else if (in[i] + 1 == ou[i]) { y++; } else z++; } } if (z) { cout << "The door cannot be opened." << endl; continue; } if ((x == 1 && y == 1) || (x == 0 && y == 0)) { cout << "Ordering is possible." << endl; continue; } else { cout << "The door cannot be opened." << endl; } } return 0; }
hdu 1116 Play on Words (欧拉回路)
最新推荐文章于 2019-09-10 14:39:08 发布