(File IO): input:trans.in output:trans.out
时间限制: 2000 ms 空间限制: 128000 KB 具体限制
Goto ProblemSet
题目描述
随着马场的繁荣,出现了越来越多的新马种。种族之间的沟通不畅严重影响了马场的和谐。这时,科学家发明了马语翻译机器人,正好可以解决这一难题。
机器人有
M
M
M 种,每种机器人能完成
K
K
K 个马种之间的语言翻译。问,利用这些机器人,能否实现
1
1
1 种群和
N
N
N 种群的马语翻译。 若可以,找到翻译过程至少需要用到多少种语言。
输入
第一行三个整数
N
N
N,
K
K
K 和
M
M
M,分别表示语言数, 每个机器人能翻译的语言数, 机器人的数量。
接下来
M
M
M行,每行
K
K
K 个整数。表示每个机器人可以翻译的语言编号(编号从
1
1
1 到
N
N
N)。
输出
输出最少转换语言的次数。如果无法完成翻译,输出
−
1
-1
−1。
样例输入
9 3 5
1 2 3
1 4 5
3 6 7
5 6 7
6 8 9
样例输出
4
【样例解释】
1
−
3
−
6
−
9
1-3-6-9
1−3−6−9 或者
1
−
5
−
6
−
9
1-5-6-9
1−5−6−9
数据范围限制
40
40
40%的数据
N
<
=
100
N<=100
N<=100,
1
<
=
K
<
=
20
,
M
<
=
40
1<=K<=20, M<=40
1<=K<=20,M<=40。
100
100
100%的数据
1
<
=
N
<
=
100000
1<=N<=100000
1<=N<=100000,
1
<
=
K
<
=
1000
,
1
<
=
M
<
=
1000
1<=K<=1000, 1<=M<=1000
1<=K<=1000,1<=M<=1000。
解题思路
这是一道图论题目,要求出从语言
1
1
1到语言
n
n
n的最短路,因为
N
N
N比较大,显然用
b
f
s
bfs
bfs(或
s
p
f
a
spfa
spfa)效率更高,但是关键在于怎么建图。
对每个机器人建图?
每两个机器人如果有共同的语言就连一条边。
枚举两个机器人,枚举机器人的语言。
时间复杂度
O
(
K
M
2
)
O(KM^2)
O(KM2),显然超时。
对每种语言建图?
对每一个机器人的所以语言两两建图。
枚举一个机器人,枚举机器人的两种语言。
时间复杂度
O
(
M
K
2
)
O(MK^2)
O(MK2),显然超时。
换个思路,对机器人和语言同时建图:把机器人变成点,与语言连边,通往机器人的边权为
1
1
1,其余为零。
那么最终的结果就是从语言1到语言n所经过的节点数
/
(
d
i
v
)
2
+
1
/(div) 2 + 1
/(div)2+1
代码
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<iomanip>
#include<cmath>
using namespace std;
int h,t,q[500000],n,m,k,dis[200005],head[200005],x,l;
bool v[200005];
struct c {
int x,next;
} a[200000];
void bfs()
{
int x1;
v[1]=1;
q[1]=1;
h=0;
t=1;
while(h<t) {
h++;
x1=q[h];
for(int i=head[x1]; i; i=a[i].next) {
if(!v[a[i].x]) {
dis[a[i].x]=dis[x1]+1;
v[a[i].x]=1;
q[++t]=a[i].x;
}
}
}
}
void add(int x,int y)
{
a[++l].x=y;
a[l].next=head[x];
head[x]=l;
}
int main()
{
freopen("trans.in","r",stdin);
freopen("trans.out","w",stdout);
scanf("%d%d%d",&n,&k,&m);
for(int i=1; i<=m; i++)
for(int j=1; j<=k; j++) {
scanf("%d",&x);
add(x,i+n);
add(i+n,x);
}
bfs();
if (v[n])
printf("%d",dis[n]/2+1);
else
cout<<-1;
}