Saturday, March 11, 2017

Solution of Light OJ 1111 - Best Picnic Ever

/*  Bismillahir Rahmanir Rahim
    Solution-Using BFS
*/
#include<bits/stdc++.h>
#define fi(n, m)     for(int i=n; i<=m; i++)
using namespace std;
vector<int>vt[1009];
int ar[100], cnt[1009], vis[1009], n, m, k, ans;

void bfs(int st){
    fi( 0, n) vis[i]=0;
    vis[st]=1;
    queue<int>q;
    q.push(st);
    cnt[st]++; //counting-how many people reach here(this node)
    if(cnt[st]==k) ans++; //if(counter[this node]==total people)
    while(!q.empty()){
        int u=q.front();
        q.pop();
        for(int j=0; j<vt[u].size(); j++){
            int v=vt[u][j];
            if(!vis[v]){
                q.push(v);
                vis[v]=1;
                cnt[v]++;  //same as previous
                if(cnt[v]==k) ans++; //same as previous
            }
        }
    }
}

int main(){
    int t, cs=1, u, v;
    cin>>t;
    while(t--){
        ans=0;
        cin>>k>>n>>m;
        fi(0, k-1) cin>>ar[i];
        fi(1, m){
            cin>>u>>v;
            vt[u].push_back(v);
        }
        fi(0, n) cnt[i]=0;
        for(int x=0; x<k; x++){
            bfs(ar[x]);   //BFS from all people location (node)
        }
        cout<<"Case "<<cs++<<": "<<ans<<endl;
        fi(0, n) vt[i].clear();
    }
    return 0;
}

1 comment: