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 NN nodes
in total.
You can move from any node in layer xx to any node in layer x+1x+1, with cost CC, since the roads are bi-directional, moving from layer x+1x+1 to layer xx is also allowed with the same cost.
Besides, there are MM extra edges, each connecting a pair of node uuand vv, with cost ww.
Help us calculate the shortest path from node 11 to node NN.
The first line has a number TT (T≤20T≤20) , indicating the number of test cases.
For each test case, first line has three numbers NN, MM (0≤N0≤N, M≤105M≤105) and CC(1≤C≤1031≤C≤103), which is the number of nodes, the number of extra edges and cost of moving between adjacent layers.
The second line has NN numbers lili (1≤li≤N1≤li≤N), which is the layer ofithith node belong to.
Then come NN lines each with 33 numbers, uu, vv (1≤u1≤u, v≤Nv≤N, u≠vu≠v) and ww (1≤w≤1041≤w≤104), which means there is an extra edge, connecting a pair of node uu and vv, with cost ww.
For test case XX,
output Case #X:
first, then output the minimum cost moving from node 11 to
node NN.
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);
}
}