fork download
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pb push_back
#define fi first
#define se second
#define mp make_pair
#define all(cont) cont.begin(), cont.end()

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
#ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#endif
    ll tt = 1;
    ll N;
    string str;
    while(getline(cin,str))
    {
        N = stoll(str);
        ll M;
        string val,a,b;
        vector<string>arr(N);
        unordered_map<string,bool>visited;
        for(ll i=0;i<N;i++)
        {

            cin>>val;
            arr[i] = val;
            visited[val] = false;
        }
        unordered_map<string,ll>indegree;
        unordered_map<string,vector<string>>adj;
        cin>>M;
        for(ll i=0;i<M;i++)
        {
            cin>>a>>b;
            adj[a].pb(b);
            indegree[b]++;
        }
        string ans;
        while(true)
        {
            bool flag = false;
            for(int i=0;i<N;i++)
            {
                if(indegree[arr[i]]==0 && !visited[arr[i]])
                {
                    ans += arr[i]+" ";
                    for(auto it:adj[arr[i]])
                        indegree[it]--;
                    flag = true;
                    visited[arr[i]] = true;
                }
            }
            if(flag==false)
                break;
        }
        cout<<"Case #"<<tt<<": Vivek should drink beverages in this order: "<<ans<<endl;
        cout<<endl;
        tt++;
        getline(cin,str);
        getline(cin,str);
    }

    return 0;


}
Success #stdin #stdout 0s 4296KB
stdin
8
a
b
c
d
e
f
s
t
6
a e
a b
c d
e f
s t
a t

8
s
a
b
e
f
c
d
t
6
a e
a b
c d
e f
s t
a t

5
A
B
C
D
E
5
C A
D A
B D
E B
E C
stdout
Case #1: Vivek should drink beverages in this order: a b c d e f s t 

Case #2: Vivek should drink beverages in this order: s a b e f c d t 

Case #3: Vivek should drink beverages in this order: E B C D A