UVA 247 Solution- Calling Circles

/* Solved by using DFS- Timestamp &  DFS-Cycle*/


/*
uva Id: shoaib05
uva 247 - Calling Circles
Accepted Time: 0.043
*/

#include<iostream>
#include<string.h>
#include<stack>
#include<algorithm>
#include<vector>
#include<map>
#include<string>

using namespace std;

typedef pair<int,int> pii;
int table[30][30],trans[30][30],vis[30],f[30],d[30],counter,m,n;
map<string,int> map1;
map<int,string> map2;
map<string,int>::iterator it;
vector< pair<int,int> > vec;
vector<string> output;

void reset()
{
memset(table,0,sizeof(table));
memset(trans,0,sizeof(trans));
memset(vis,0,sizeof(vis));
memset(f,0,sizeof(f));
map1.clear();
map2.clear();
}

bool mysort(pair<int,int> p1,pair<int,int> p2)
{
if(p1.second>p2.second)
return true;
return false;
}


void dfs(int x)
{
int i;
d[x]=counter;
vis[x]=1;
for(i=0;i<m;i++)
{
if(table[x][i]==1 && vis[i]==0)
{
counter++;
vis[i]=1;
dfs(i);
}
}
counter++;
f[x]=counter;
}

void topological(int x)
{
int i;
vis[x]=1;
for(i=0;i<m;i++)
{
if(trans[x][i]==1 && vis[i]==0)
{
vis[i]=1;
topological(i);
}
}
output.push_back(map2[x]);
}

int main()
{
int i,j,k,test,u,v;
string s1,s2;
test=1;
while(true)
{
cin>>m>>n;
if(m==0 && n==0)
break;
if(test>1)
cout<<endl;
cout<<"Calling circles for data set "<<test++<<":"<<endl;
reset();
k=0;
for(i=0;i<n;i++)
{
cin>>s1>>s2;
it=map1.find(s1);
if(it!=map1.end())
u=it->second;
else
{
map1[s1]=k;
map2[k]=s1;
u=k;
k++;
}
it=map1.find(s2);
if(it!=map1.end())
v=it->second;
else
{
map1[s2]=k;
map2[k]=s2;
v=k;
k++;
}
table[u][v]=1;
trans[v][u]=1;
}
counter=0;
for(i=0;i<m;i++)
{
if(vis[i]==0)
{
counter++;
dfs(i);
}
}
vec.clear();
for(i=0;i<m;i++)
vec.push_back(make_pair<int,int>(i,f[i]));
sort(vec.begin(),vec.end(),mysort);
memset(vis,0,sizeof(vis));
for(i=0;i<m;i++)
{
j=vec[i].first;
if(vis[j]==0)
{
output.clear();
topological(j);
for(k=0;k<output.size()-1;k++)
cout<<output[k]<<", ";
cout<<output[k]<<endl;
}
}
}
return 0;
}

Comments

Popular posts from this blog

uva 679 - Dropping Balls Solution

uva 481 - What Goes Up Solution

uva-10077 Solution --- The Stern-Brocot Number System