Sunday, 17 January 2016

UVa 247 - Calling Circles

The question involves finding all SCC (Strongly Connected Components) and printing them.
Here the question can be solved easily due to smaller constraints (n<=25).

As the constraints are small we can apply Floyd Warshall Algorithm to calculate graph[i][j] which is "1" if we can reach to "j" from "i" else it is "0".

Then for each "i" check if graph[i][j] and graph[j][i] both are set as it implies that both can be reached from each other and so they can be included in same SCC.Take a mk[] array to mark the elements already taken and print each SCC for each unmarked "i".

Check the code for further reference :


//\\__ hr1212 __//\\

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef map<int,int> mi;

#define si(a) scanf("%d",&a)
#define sii(a,b) scanf("%d %d",&a,&b)
#define siii(a,b,c) scanf("%d %d %d",&a,&b,&c)
#define pi(a) printf("%d\n",a)
#define nl printf("\n");
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define f(i,a,b) for(i=a;i<b;i++)
#define rf(i,a,b) for(i=a;i>=b;i--)
#define clr(x,a) memset(x,a,sizeof(x))
#define MAX 1000100
#define MOD 1000000007

int n,m,mk[50],graph[100][100];

map<string,int> mm;
vector<string> w;

int main(){
    int tt=1,r,k,i,c=0,x=0,y=0,j,t,l,z,x1=0,y1=0;
    ll ans=0;string p,q;

    while(sii(n,m)){
        if(n==0 && m==0)
            break;
        if(tt!=1)
            nl;
        z=0;
        mm.clear();
        w.clear();
        clr(mk,0);
        clr(graph,0);
        f(i,0,m){
            cin>>p>>q;
            if(mm.find(p)==mm.end()){
                mm[p]=z++;
                w.pb(p);
            }
            if(mm.find(q)==mm.end()){
                mm[q]=z++;
                w.pb(q);
            }
            x=mm[p];y=mm[q];
            graph[x][y]=1;
        }
        f(k,0,n){
            f(i,0,n){
                f(j,0,n){
                    graph[i][j]|=(graph[i][k]&&graph[k][j]);
                }
            }
        }
        printf("Calling circles for data set %d:\n",tt++);
        f(i,0,n){
            vi v;
            if(!mk[i]){
                mk[i]=1;
                v.pb(i);
                f(j,0,n){
                    if(!mk[j]){
                        if(graph[i][j] && graph[j][i]){
                            v.pb(j);
                            mk[j]=1;
                        }
                    }
                }
            f(k,0,v.size()){
                cout<<w[v[k]];
                if(k!=v.size()-1)
                    cout<<", ";
            }
            nl;
            }
        }
    }

    return 0;
}

No comments:

Post a Comment