UVA 11838 - Come and Go Solution
Solution in C++:
///**********ALLAH IS ALMIGHTY************///
///AH Tonmoy
///Department of CSE,23rd batch
///Islamic University,Bangladesh
#include<bits/stdc++.h>
using namespace std;
vector<int>adj[5000],adj2[5000];
bool vis[5000]= {false},vis2[5000]= {false};
int stime[5000]= {0},ftime[5000]= {0};
int t=0;
stack<int>st;
void dfs(int r)
{
vis[r]=true;
t++;
stime[r]=t;
for(int i=0; i<adj[r].size(); i++)
{
int x=adj[r][i];
if(!vis[x])
{
vis[x];
dfs(x);
}
}
t++;
ftime[r]=t;
st.push(r);
}
void scc_dfs(int r)
{
vis2[r]=true;
for(int i=0; i<adj2[r].size(); i++)
{
int x=adj2[r][i];
if(!vis2[x])
{
vis2[x]=true;
scc_dfs(x);
}
}
}
int main()
{
int i,x,v,w,p,r,n,m;
while(cin>>n>>m)
{
if(n==0&&m==0)
break;
memset(stime,0,sizeof(stime));
memset(ftime,0,sizeof(ftime));
memset(vis,0,sizeof(vis));
memset(vis2,0,sizeof(vis2));
int i,x, t=0,c=0;
for(i=0; i<=n; i++)
{
adj[i].clear();
adj2[i].clear();
}
for(i=0; i<m; i++)
{
cin>>v>>w>>p;
if(p==1)
{
adj[v].push_back(w);
adj2[w].push_back(v);
}
else if(p==2)
{
adj[v].push_back(w);
adj[w].push_back(v);
adj2[v].push_back(w);
adj2[w].push_back(v);
}
}
for(i=1; i<=n; i++)
{
if(!vis[i])
dfs(i);
}
while(!st.empty())
{
x=st.top();
if(!vis2[x])
{
c++;
scc_dfs(x);
}
st.pop();
}
if(c==1)
cout<<"1"<<endl;
else
cout<<"0"<<endl;
}
}
No comments