Drunk LightOJ - 1003 (拓扑排序判断环)

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
2
2
soda wine
water wine
3
soda wine
water wine
wine water
Sample Output
Case 1: Yes
Case 2: No

给每个字符串编号后判断有没有环
AC的C++程序如下:

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstdio>
#include<cstring>
#include<string>
#include<vector>
#include<map>
using namespace std;
const int maxn = 10005;
int into[maxn], order[maxn];
vector<int> g[maxn];
int  m;
int main()
{
    int t, kase = 1;
    cin >> t;
    while (t--)
    {
        cin >> m;
        map<string, int> ma;
        string src, dest;
        queue<int> q;
        memset(into, 0, sizeof(into));
        for (int i = 0; i <= m; i++) g[i].clear();
        int no = 1;//给每个字符串编号
        for (int i = 0; i < m; i++)
        {
            cin >> src >> dest;
            if (!ma.count(src)) ma[src] = no++;
            if (!ma.count(dest)) ma[dest] = no++;
            into[ma[dest]]++;
            g[ma[src]].push_back(ma[dest]);
        }
        int len = 1;
        for (int i = 1; i <no; i++)
        {
            if (into[i] == 0) q.push(i);
        }
        while (!q.empty())
        {
            int front = q.front();
            q.pop();
            order[len++] = front;
            for (int i = 0; i < g[front].size(); i++)
            {
                into[g[front][i]]--;

                if (into[g[front][i]] == 0) q.push(g[front][i]);
            }
        }
        printf("Case %d: ",kase++);
        if (len < no) cout << "No" << endl;
        else  cout << "Yes" << endl;

    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/jinduo16/article/details/81772044