UVA 567 Risk Solution
Solve in C++:
using namespace std;
vector<int>vec[1000];
int level[1000];
void bfs(int s,int d)
{
int vis[1000]= {0};
queue<int>q;
vis[s]=1;
level[s]=0;
q.push(s);
while(!q.empty ())
{
int x=q.front();
for(int l=0; l<vec[x].size(); l++)
{
int y=vec[x][l];
if(vis[y]==0)
{
vis[y]=1;
level[y]=level[x]+1;
q.push(y);
}
}
q.pop();
}
printf("%2d to %2d: %d\n", s, d, level[d]);
}
int main()
{
int p,q,r,s,h,c=0;
while(cin>>p)
{
for(int i=0; i<p; i++)
{
cin>>q;
vec[1].push_back(q);
vec[q].push_back(1);
}
for(int j=2; j<20; j++)
{
cin>>r;
for(int i=0; i<r; i++)
{
cin>>h;
vec[j].push_back(h);
vec[h].push_back(j);
}
}
cin>>s;
printf("Test Set #%d\n",++c);
int s1,s2;
for(int k=0; k<s; k++)
{
cin>>s1>>s2;
bfs(s1,s2);
}
cout<<endl;
for(int i=0; i<=20; i++)
{
vec[i].clear();
}
}
return 0;
}
- ///**********ALLAH IS ALMIGHTY************///
- ///AH Tonmoy
- ///Department of CSE
- ///Islamic University,Bangladesh
using namespace std;
vector<int>vec[1000];
int level[1000];
void bfs(int s,int d)
{
int vis[1000]= {0};
queue<int>q;
vis[s]=1;
level[s]=0;
q.push(s);
while(!q.empty ())
{
int x=q.front();
for(int l=0; l<vec[x].size(); l++)
{
int y=vec[x][l];
if(vis[y]==0)
{
vis[y]=1;
level[y]=level[x]+1;
q.push(y);
}
}
q.pop();
}
printf("%2d to %2d: %d\n", s, d, level[d]);
}
int main()
{
int p,q,r,s,h,c=0;
while(cin>>p)
{
for(int i=0; i<p; i++)
{
cin>>q;
vec[1].push_back(q);
vec[q].push_back(1);
}
for(int j=2; j<20; j++)
{
cin>>r;
for(int i=0; i<r; i++)
{
cin>>h;
vec[j].push_back(h);
vec[h].push_back(j);
}
}
cin>>s;
printf("Test Set #%d\n",++c);
int s1,s2;
for(int k=0; k<s; k++)
{
cin>>s1>>s2;
bfs(s1,s2);
}
cout<<endl;
for(int i=0; i<=20; i++)
{
vec[i].clear();
}
}
return 0;
}
No comments