This is a very easy problem, your task is just calculate el camino más corto en un gráfico, and just sólo hay que cambiar un poco el algoritmo. If you do not understand a word of this paragraph, just move on.
The Nya graph is an undirected graph with layers
. Each node in the graph belongs to a layer, there are
N
N nodes in total.
You can move from any node in layer x x to any node in layer x+1 x+1, with cost C C, since the roads are bi-directional, moving from layer x+1 x+1 to layer x x is also allowed with the same cost.
Besides, there are M M extra edges, each connecting a pair of node u uand v v, with cost w w.
Help us calculate the shortest path from node 1 1 to node N N.
The first line has a number T T ( T≤20 T≤20) , indicating the number of test cases.
For each test case, first line has three numbers N N, M M ( 0≤N 0≤N, M≤105 M≤105) and C C( 1≤C≤103 1≤C≤103), which is the number of nodes, the number of extra edges and cost of moving between adjacent layers.
The second line has N N numbers li li ( 1≤li≤N 1≤li≤N), which is the layer of ith ith node belong to.
Then come N N lines each with 3 3 numbers, u u, v v ( 1≤u 1≤u, v≤N v≤N, u≠v u≠v) and w w ( 1≤w≤104 1≤w≤104), which means there is an extra edge, connecting a pair of node u u and v v, with cost w w.
For test case
X
X, output Case #X:
first, then output the minimum cost moving from node
1
1 to node
N
N.
If there are no solutions, output −1 −1.
2
3 3 3
1 3 2
1 2 1
2 3 1
1 3 3
3 3 3
1 3 2
1 2 2
2 3 2
1 3 4
Case #1: 2
Case #2: 3
Hint
#include<bits/stdc++.h>
using namespace std;
const int N=200000;
const int inf=0x3f3f3f3f;
int vv[N],vis[N],head[N],dis[N],lay[N];
int ans,n,m,c,cnt;
struct node
{
int w,v,next;
}edge[20*N];
void init()
{
memset(vv,0,sizeof(vv));
memset(vis,0,sizeof(vis));
memset(head,-1,sizeof(head));
memset(dis,inf,sizeof(dis));
}
void add(int u,int v,int w)
{
cnt++;
edge[cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt;
}
void SPFA()
{
queue<int>q;
vis[1]=1;
dis[1]=0;
q.push(1);
int i,u,v,w;
while(!q.empty())
{
u=q.front();
q.pop();
vis[u]=0;
for(i=head[u];i!=-1;i=edge[i].next)
{
v=edge[i].v;
w=edge[i].w;
if(dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
if(vis[v]==0)
{
vis[v]=1;
q.push(v);
}
}// µãµ½µã½¨±ß
}
}
}
int main()
{
int t;
cin>>t;
int u,v,w;
for(int i=1;i<=t;i++)
{
cnt=0;
init();
cin>>n>>m>>c;
for(int j=1;j<=n;j++)
{
cin>>u;
lay[j]=u;
vv[u]=1;
}
for(int j=1;j<n;j++)
if(vv[j]&&vv[j+1])
{
add(j+n,j+n+1,c);
add(j+n+1,j+n,c);
}
for(int j=1;j<=n;j++)
{
add(n+lay[j],j,0);
if(lay[j]>1) add(j,lay[j]+n-1,c);
if(lay[j]<n) add(j,lay[j]+n+1,c);
}
for(int j=1;j<=m;j++)
{
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
SPFA();
ans=dis[n];
if(ans!=inf)
{
printf("Case #%d: %d\n",i,ans);
}
else
printf("Case #%d: -1\n",i);
}
}