题目描述
整个回廊可以看作一个n 个点m 条边的无向图,每条边走动花费的时间为1。辉夜、永琳、铃仙、因幡帝等k 个人或兔子可以通过传送阵分别进入这个图上的k 个特殊的点,然后去寻找闯入者。但是在寻找闯入者之前,他们要聚集到一个点,以增强战斗力。注意,可以先到的人停下不走等后来的人。
闯入者不知道回廊的规则,因此被困住,对辉夜等k 个人的行动没有影响。而辉夜等k个人必须按照回廊的规则走动。
回廊的规则如下:每个点有一个颜色,一共4 种颜色,红、蓝、黄、绿,分别以R、B、Y、G 表示。走动时必须在第4p+1 步到4p+4 步的时候走四种不同的颜色,当然最后一个不完整的周期内也不能走动相同颜色。注意,起点算第1 步。
现在给定k 个起点,辉夜想知道他们最短多长时间能够汇合,若不能汇合输出-1。
输入
第一行一个Case,表示测试点编号。
第二行两个数n 和m,表示图有n 个点m 条边。
第三行一个k,表示有k 个人。
第四行k 个数,表示k 个入口的编号。
第五行一个长度为n 的字符串,仅包含RBYG,表示n 个点的颜色。
下面 m 行每行两个数,ui,vi,表示第 i 条边连接了ui和vi。
输出
一个数表示最短汇合时间,不能汇合输出-1。
样例输入
<span style="color:#333333"><span style="color:#333333">1
5 4
4
1 2 3 4
RRRRG
1 5
2 5
3 5
4 5</span></span>
样例输出
<span style="color:#333333"><span style="color:#333333">1</span></span>
提示
数据范围
对于100%的数据,保证k>=2。
测试点编号 | n | m | k |
1 | ≤8≤8 | ≤16≤16 | ≤5≤5 |
2 | ≤30000≤30000 | =n−1=n−1 | ≤5≤5 |
3 | |||
4 | ≤30000≤30000 | ≤150000≤150000 | ≤5≤5 |
5 | |||
6 | |||
7 | ≤50000≤50000 | ≤200000≤200000 | ≤10≤10 |
8 | |||
9 | |||
10 |
来源
题解:
由于我们只关心每四步走了哪几种颜色,所以我们可以设计Dist[i][j]表示走到i点,在这个四步之内每一种颜色的情况,然后用dijkstra跑一遍即可。
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
int Case,n,m,k,a[15],co[50005],V[400005],nex[400005],las[50005],tot;
int Dist[15][50005][16],dist[505][50005],ans=1e9;
struct Node{int x,y;};
queue<Node>que;
char ch[50005];
void add(int t1,int t2)
{
V[++tot]=t2;nex[tot]=las[t1];las[t1]=tot;
V[++tot]=t1;nex[tot]=las[t2];las[t2]=tot;
}
int main()
{
scanf("%d%d%d%d",&Case,&n,&m,&k);
for(int i=1;i<=k;++i)scanf("%d",&a[i]);
scanf(" %s",ch+1);
for(int i=1;i<=n;++i)
{
if(ch[i]=='R')co[i]=0;
if(ch[i]=='B')co[i]=1;
if(ch[i]=='Y')co[i]=2;
if(ch[i]=='G')co[i]=3;
}
for(int i=1,t1,t2;i<=m;++i)scanf("%d%d",&t1,&t2),add(t1,t2);
for(int i=1;i<=k;++i)
{
for(int j=1;j<=n;++j)
for(int t=0;t<16;++t)Dist[i][j][t]=1e9;
Dist[i][a[i]][1<<co[a[i]]]=0;
que.push((Node){a[i],1<<co[a[i]]});
while(!que.empty())
{
Node t=que.front();que.pop();
int h=las[t.x];
while(h)
{
if((Dist[i][t.x][t.y]+1)%4==0)
{
if(Dist[i][V[h]][1<<co[V[h]]]>Dist[i][t.x][t.y]+1)
{
Dist[i][V[h]][1<<co[V[h]]]=Dist[i][t.x][t.y]+1;
que.push((Node){V[h],1<<co[V[h]]});
}
h=nex[h];continue;
}
if((1<<co[V[h]])&t.y){h=nex[h];continue;}
if(Dist[i][V[h]][t.y|(1<<co[V[h]])]>Dist[i][t.x][t.y]+1)
{
Dist[i][V[h]][t.y|(1<<co[V[h]])]=Dist[i][t.x][t.y]+1;
que.push((Node){V[h],t.y|(1<<co[V[h]])});
}
h=nex[h];
}
}
}
for(int i=1;i<=k;++i)
for(int j=1;j<=n;++j)
{
dist[i][j]=1e9;
for(int t=0;t<16;++t)dist[i][j]=min(dist[i][j],Dist[i][j][t]);
}
for(int i=1;i<=n;++i)
{
int ls=-1;
for(int j=1;j<=k;++j)ls=max(ls,dist[j][i]);
ans=min(ans,ls);
}
if(ans!=1e9)cout<<ans;
else cout<<-1;
}