2130: hipercijevi
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 704 Solved: 140
SubmitStatusWeb 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
HINT
题意:求1到n经过的站点。 首先一个管道内的站能直接到达,不需要步数,当跨到另一个管道是相当经过了一个站,加上起始点和终点就是答案。比如第一样例 1 3 6 9 第二个样例 1 12 15
思路: RT 这里不同的是需要外设一个虚点连通同一个管道的点, 但是走过虚点也加了一, 所以最后要除2 + 1,经过虚点的次数和经过的站两者,其实最后相差1。
另外不加外挂超时了 = =。
Source
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <string>
#include <ctime>
#include <queue>
#include <stack>
#include <vector>
#define sc(a) scanf("%d", &a)
#define FF(a, b, c) for(int a=b;a<=c;++a)
#define mem(a) memset(a, 0, sizeof(a))
using namespace std;
typedef pair<int,int> Pii;
const int MAXN = 2100000;
typedef long long LL;
int n, k, m, cnt;
int head[MAXN];
bool vis[MAXN];
struct edge
{
int from, to, w;
} G[MAXN];
struct node
{
int cur;
int step;
};
inline int read()
{
int x=0, f=1;
char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') {x=x*10+ch-'0';ch=getchar();}
return x*f;
}
void init()
{
memset(head, -1, sizeof(head));
memset(vis, false, sizeof(vis));
cnt=0;
}
void add(int u, int v, int w)
{
G[cnt].to = v;
G[cnt].w=w;
G[cnt].from = head[u];
head[u]=cnt++;
}
int bfs()
{
queue<node> q;
node u;
vis[1]=true;
u.cur=1;
u.step=0;
q.push(u);
while(!q.empty())
{
u=q.front();
q.pop();
for(int i=head[u.cur]; ~i; i=G[i].from)
{
node v;
v.cur=G[i].to;
if(!vis[v.cur])
{
v.step=u.step+1;
if(v.cur==n)
{
return v.step/2+1;
}
q.push(v);
vis[v.cur]=true;
}
}
}
return -1;
}
int main()
{
int T, u;
scanf("%d", &T);
while(T--)
{
scanf("%d %d %d", &n, &k,&m);
init();
for(int i=1; i<=m; ++i)
{
int from=i+n;
for(int j=1; j<=k; ++j)
{
u=read();
add(u, from, 1);
add(from, u, 1);
}
}
int ans = bfs();
printf("%d\n", ans);
}
}