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 abefore 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 |
题目大意:
一共有M种喝水的限制,要想喝B,那么一定要先喝A.
问能否在结束的时候将所有的种类的水都喝了。
思路:
1、对于有向边的限制条件,不难想到有向图的拓扑排序。
2、问能否将所有种类的水都喝掉,那么肯定这是一个拓扑排序判断环的工作。
对于拓扑排序的结果,如果所有点最终的度都是0,那么很显然没有环,反之亦然。
Ac代码:
#include<stdio.h>
#include<string.h>
#include<map>
#include<vector>
#include<iostream>
#include<queue>
using namespace std;
int degree[50060];
vector<int >mp[50060];
int n;
void top()
{
int cont=0;
queue<int >s;
for(int i=1;i<=n;i++)
{
if(degree[i]==0)
{
cont++;
s.push(i);
}
}
while(!s.empty())
{
int u=s.front();
s.pop();
for(int i=0;i<mp[u].size();i++)
{
int v=mp[u][i];
degree[v]--;
if(degree[v]==0)
{
cont++;
s.push(v);
}
}
}
if(cont==n)printf("Yes\n");
else printf("No\n");
}
int main()
{
int kase=0;
int t;
scanf("%d",&t);
while(t--)
{
map<string, int >s;
for(int i=1;i<=40060;i++)mp[i].clear();
memset(degree,0,sizeof(degree));
n=0;
int m;
scanf("%d",&m);
for(int i=0;i<m;i++)
{
char a[150];
char b[150];
scanf("%s%s",a,b);
if(s[a]==0)
{
n++;
s[a]=n;
}
if(s[b]==0)
{
n++;
s[b]=n;
}
degree[s[b]]++;
mp[s[a]].push_back(s[b]);
}
printf("Case %d: ",++kase);
top();
}
}