http://www.lightoj.com/volume_showproblem.php?problem=1003
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 10 characters 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 |
看代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <string>
#define SI(T)int T;scanf("%d",&T)
using namespace std;
const int SIZE=1e4+10;
const int maxn=1<<30;
map<string,int> ma;
vector<vector<int> >G;
int cnt[SIZE];
bool vis[SIZE];
bool euler(int num){//存在某个分量无环则可能喝醉,返回yes,这一题的一个bug,手头上没有求弱联通分量的算法
queue<int> q;
for(int i=0;i<num;i++){
if(cnt[i]==0)q.push(i);
}
while(!q.empty()){
int u=q.front();
q.pop();
num--;
for(int i=0;i<G[u].size();i++){
int v=G[u][i];
cnt[v]--;
if(cnt[v]==0)q.push(v);
}
}
if(num==0)return true;
return false;
}
int main()
{
//freopen("F://in.txt","r",stdin);
SI(T);
for(int cas=1;cas<=T;cas++){
memset(cnt,-1,sizeof(cnt));
int m,num=0;
ma.clear();
char s1[15],s2[15];
scanf("%d",&m);
G.clear();
G.resize(SIZE);
for(int i=0;i<m;i++){
scanf("%s%s",s1,s2);
if(!ma.count(s1))ma[s1]=num++;
if(!ma.count(s2))ma[s2]=num++;
int u=ma[s1];
int v=ma[s2];
G[u].push_back(v);
if(cnt[u]==-1)cnt[u]=0;
if(cnt[v]==-1)cnt[v]=1;
else cnt[v]++;
}
memset(vis,false,sizeof(vis));
if(euler(num))printf("Case %d: Yes\n",cas);
else printf("Case %d: No\n",cas);
}
return 0;
}