Problem:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=&problem=508&mosmsg=Submission+received+with+ID+17140993
Solve:
#include<bits/stdc++.h>
using namespace std;
vector<int>v[23];
int bfs(int s,int d)
{
int visited[25];
memset(visited,-1,sizeof(visited));
int w;
queue<int>q;
visited[s]=0;
q.push(s);
int u,p;
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=0; i<v[u].size(); i++)
{
p=v[u][i];
if(visited[p]==-1)
{
visited[p]=visited[u]+1;
q.push(p);
if(p==d) break;
}
}
}
w= visited[d]-visited[s];
return w;
}
int main()
{
int a,b,c,d,e,f,g,h=1,i,j;
while(scanf("%d",&a)==1)
{
b=1;
for(i=1; i<=a; i++)
{
scanf("%d",&c);
v[b].push_back(c);
v[c].push_back(b);
}
b++;
for(i=1; i<=18; i++)
{
scanf("%d",&a);
for(j=1; j<=a; j++)
{
scanf("%d",&c);
v[b].push_back(c);
v[c].push_back(b);
}
b++;
}
scanf("%d",&e);
printf("Test Set #%d\n",h);
h++;
for(i=1; i<=e; i++)
{
scanf("%d%d",&f,&g);
c=bfs(f,g);
printf("%2d to %2d: %d\n",f,g,c);
}
printf("\n");
for(i=0; i<=21; i++) v[i].clear();
}
}
No comments:
Post a Comment