2130: hipercijevi
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 798 Solved: 166
Submit Status Web Board
Description
在遥远的星系, 最快的交通方式是用某种管道。 每个管道直接互相连接N个站。 那么我们从第一个站到第N个站最少要经过多少个站呢?
Input
输入文件的第一行为T表示有T组数据
每个数据第一行包含三个正整数 N (1<=N<=100000) 表示站的个数; K (1<=K<=1000) 表示一个管道直接连接了多少个站; M (1<=M<=1000) 表示管道的数量。
接下来的M行, 每行包含一个管道的描述: K个正整数, 表示这个管道连接的K个站的编号。
Output
输出文件T行,每行包含一个正整数,表示从第一个站到第N个站最少需要经过多少个站。 如果无法从第一个站到达第N个站,输出-1 。
Sample Input
2
9 3 5
1 2 3
1 4 5
3 6 7
5 6 7
6 8 9
15 8 4
11 12 8 14 13 6 10 7
1 5 8 12 13 6 2 4
10 15 4 5 9 8 14 12
11 12 14 3 5 6 1 13
Sample Output
4
3
思路:
对于路径长度为1的最短路相关问题,我们将其看成是一个普通的Bfs题目即可。
那么将点到管道之间的路径长度设为0,管道到点之间的路径长度设为1.
然后暴力跑Bfs即可。
本题要FastIO以及用邻接表去建才行。
否则会TLE.
Ac代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<vector>
using namespace std;
struct node
{
int from,to,next;
}e[2000504];
int cont;
int dist[400050];
int vis[400050];
int head[400050];
int Scan()
{
int res = 0, ch, flag = 0;
if((ch = getchar()) == '-') //判断正负
flag = 1;
else if(ch >= '0' && ch <= '9') //得到完整的数
res = ch - '0';
while((ch = getchar()) >= '0' && ch <= '9' )
res = res * 10 + ch - '0';
return flag ? -res : res;
}
void add(int from,int to)
{
e[cont].to=to;
e[cont].next=head[from];
head[from]=cont++;
}
int n,k,m;
void Bfs()
{
memset(vis,0,sizeof(vis));
for(int i=1;i<=n+m;i++)dist[i]=0x3f3f3f3f;
dist[1]=1;
vis[1]=1;
queue<int>s;
s.push(1);
while(!s.empty())
{
int u=s.front();
s.pop();
for(int i=head[u];i!=-1;i=e[i].next)
{
int v=e[i].to;
int tmp=0;
if(v<=n)tmp++;
if(dist[v]>dist[u]+tmp)
{
dist[v]=dist[u]+tmp;
if(vis[v]==0)
{
s.push(v);
}
}
}
}
if(dist[n]==0x3f3f3f3f)printf("-1\n");
else printf("%d\n",dist[n]);
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d%d",&n,&k,&m);
cont=0;
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
for(int j=1;j<=k;j++)
{
int x;
x=Scan();
add(x,i+n);
add(n+i,x);
}
}
Bfs();
}
}