Light OJ 1003 – Drunk

Problem Link : http://www.lightoj.com/volume_showproblem.php?problem=1003


/*
         +-+ +-+ +-+
         |R| |.| |S|
         +-+ +-+ +-+
 */

#include <bits/stdc++.h>

#define pii             pair <int,int>
#define sc              scanf
#define pf              printf
#define Pi              2*acos(0.0)
#define ms(a,b)         memset(a, b, sizeof(a))
#define pb(a)           push_back(a)
#define MP              make_pair
#define db              double
#define ll              long long
#define EPS             10E-10
#define ff              first
#define ss              second
#define sqr(x)          (x)*(x)
#define D(x)            cout<<#x " = "<<(x)<<endl
#define VI              vector <int>
#define DBG             pf("Hi\n")
#define MOD             100007
#define MAX             10010
#define CIN             ios_base::sync_with_stdio(0); cin.tie(0)
#define SZ(a)           (int)a.size()
#define sf(a)           scanf("%d",&a)
#define sff(a,b)        scanf("%d%d",&a,&b)
#define sfff(a,b,c)     scanf("%d%d%d",&a,&b,&c)
#define loop(i,n)       for(int i=0;i<n;i++)
#define REP(i,a,b)      for(int i=a;i<b;i++)
#define TEST_CASE(t)    for(int z=1;z<=t;z++)
#define PRINT_CASE      printf("Case %d: ",z)
#define all(a)          a.begin(),a.end()
#define intlim          2147483648
#define inf             1000000
#define ull             unsigned long long


using namespace std;

map<string,int>mp;
vector<int>graph[MAX], sorted;
int indegree[MAX];
int m,cnt;

void allclear()
{
    loop(i,cnt+1)
    {
        graph[i].clear();
        indegree[i]=0;
    }
    mp.clear();
    sorted.clear();
}

int main()
{
    ///freopen("in.txt","r",stdin);
    ///freopen("out.txt","w",stdout);
    int t;
    sf(t);
    TEST_CASE(t)
    {
        cnt=1;
        sf(m);
        loop(i,m)
        {
            string str1,str2;
            cin>>str1>>str2;
            if(mp[str1]==0)
                mp[str1]=cnt++;
            if(mp[str2]==0)
                mp[str2]=cnt++;
            graph[mp[str1]].pb(mp[str2]);
            indegree[mp[str2]]++;
        }

        REP(i,1,cnt)
        if(indegree[i]==0) sorted.pb(i);

        for(int i=0;i<SZ(sorted);i++)
            {
                int u=sorted[i];
                for(int j=0;j<SZ(graph[u]);j++)
                {
                    int v=graph[u][j];
                    indegree[v]--;
                    if(indegree[v]==0)
                        sorted.pb(v);
                }
            }

            bool test=0;
            REP(i,1,cnt)
            {
                if(indegree[i]!=0)
                {
                    test=1;
                    break;
                }
            }
            PRINT_CASE;
            if(test)
                pf("No\n");
            else
                pf("Yes\n");
            allclear();
    }
    return 0;
}


Advertisements