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
【题目链接】
题解
第一次去外校比赛,也是第一次体验被卡时间,长见识了。
卡了 vector , 得用静态数组实现的前向星(发现手写的动态链表也是超时的),如此优化应该刚好能过了。
然后优化读取 600+ms,对读取外挂再优化后就是200 ms(黑科技啊)
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#define MAX_N 102005
#define INF 0x3f3f3f3f
using namespace std;
typedef long long LL;
const int MAXS = 60*1024*1024;
char buf[MAXS],*ch;
void read(int &x){
for(++ch;*ch<=32;++ch);
for(x=0;*ch>='0';++ch) x=x*10+*ch-'0';
}
void std_init(){
ch=buf-1;
fread(buf,1,MAXS,stdin);
}
struct node{
int to,next;
};
node dat[1005*1005*2];
int pit[MAX_N];
int u;
void add_edge(int x,int y){
dat[u].next=pit[x];
dat[u].to=y;
pit[x]=u++;
}
queue<int> que;
int d[MAX_N];
int x,N,K,M;
int bfs(int s,int t){
memset(d,-1,sizeof(d));
que.push(s);
d[s] = 1;
while(!que.empty()){
int v = que.front();que.pop();
if(v == t) return (d[v]+1)/2;
for(int p = pit[v]; p; p = dat[p].next){
if(d[dat[p].to] == -1){
d[dat[p].to] = d[v]+1;
que.push(dat[p].to);
}
}
}
return -1;
}
int main()
{
// freopen("C:\\Users\\chutzpah\\Desktop\\in.txt","r",stdin);
std_init();
int T;read(T);
while(T--){
read(N);read(K);read(M);u=1;
memset(pit,0,sizeof(int)*(N+M+2));
for(int i = 1; i <= M; i++){
for(int j = 0; j < K; j++){
read(x);
add_edge(x,N+i);
add_edge(N+i,x);
}
}
printf("%d\n",bfs(1,N));
while(!que.empty()) que.pop();
}
return 0;
}