http://www.lightoj.com/volume_showproblem.php?problem=1003
1003 - Drunk
Time Limit: 2 second(s) | Memory Limit: 32 MB |
One of my friends is always drunk. So, sometimes I get a bit confused whether he is drunk or not. So, one day I was talking to him, about his drinks! He began to describe his way of drinking. So, let me share his ideas a bit. I am expressing in my words.
There are many kinds of drinks, which he used to take. But there are some rules; there are some drinks that have some pre requisites. Suppose if you want to take wine, you should have taken soda, water before it. That's why to get real drunk is not that easy.
Now given the name of some drinks! And the prerequisites of the drinks, you have to say that whether it's possible to get drunk or not. To get drunk, a person should take all the drinks.
Input
Input starts with an integer T (≤ 50), denoting the number of test cases.
Each case starts with an integer m (1 ≤ m ≤ 10000). Each of the next m lines will contain two names each in the format a b, denoting that you must have a before having b. The names will contain at most 10characters with no blanks.
Output
For each case, print the case number and 'Yes' or 'No', depending on whether it's possible to get drunk or not.
Sample Input | Output for Sample Input |
2 2 soda wine water wine 3 soda wine water wine wine water | Case 1: Yes Case 2: No |
题意:
(能说没读懂题意吗?)有 m 个关系式,在给定的字符串 a,b 串中,想喝 b 需要先把 a 喝完。喝醉的条件:所有的饮料全部喝完。
思路:
拓扑排序判断环的存在性,如果最终存在没有进队的元素,就有环,此时就不知道应该怎么喝了。
AC code:
#include<stdio.h>
#include<string>/*注意和string.h的区别*/
#include<map>/*使用*/
#include<queue>
#include<vector>
#include<algorithm>
#define AC main()
using namespace std;
const int MYDD = 1103 + 2e4;
int indegree[MYDD];
map<string, int> Map;
vector<int> vec[MYDD];
void Initalize(int m) {
for(int j = 0; j <= 2 * m; j++) {
vec[j].clear();
indegree[j] = 0;
}
Map.clear();
}
bool Topo() {
int sum = Map.size();
queue<int> q;
for(int j = 1; j <= Map.size(); j++)/* bug j < Map.size()*/
if(!indegree[j]) {
q.push(j);
sum--;
}
while(!q.empty()) {
int now = q.front();
q.pop();
for(int j = 0; j < vec[now].size(); j++) {
int temp = vec[now][j];
indegree[temp]--;
if(!indegree[temp]) {/* bug !indegree[j]*/
q.push(temp);
sum--;
}
}
}
if(sum) return false;/*存在节点的剩余,就有环*/
return true;
}
int AC {
int tt, kc = 1;
scanf("%d", &tt);
while(tt--) {
int m;
scanf("%d", &m);
Initalize(m);
for(int j = 0; j < m; j++) {
char a[32], b[32];
scanf("%s %s", a, b);
if(!Map[a]) Map[a] = Map.size();
if(!Map[b]) Map[b] = Map.size();
vec[Map[a]].push_back(Map[b]);
indegree[Map[b]]++;
}
printf("Case %d: ",kc++);
if(Topo()) puts("Yes");
else puts("No");
}
return 0;
}