This is a very easy problem, your task is just calculate el camino mas corto en un grafico, and just solo 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 nodes in total.
You can move from any node in layer x to any node in layer x + 1, with cost C, since the roads are bi-directional, moving from layer x + 1 to layer x is also allowed with the same cost.
Besides, there are M extra edges, each connecting a pair of node u and v, with cost w.
Help us calculate the shortest path from node 1 to node N.
Input
The first line has a number T (T <= 20) , indicating the number of test cases.
For each test case, first line has three numbers N, M (0 <= N, M <= 10 5) and C(1 <= C <= 10 3), which is the number of nodes, the number of extra edges and cost of moving between adjacent layers.
The second line has N numbers l i (1 <= l i <= N), which is the layer of i th node belong to.
Then come N lines each with 3 numbers, u, v (1 <= u, v < =N, u <> v) and w (1 <= w <= 10 4), which means there is an extra edge, connecting a pair of node u and v, with cost w.
Output
For test case X, output "Case #X: " first, then output the minimum cost moving from node 1 to node N.
If there are no solutions, output -1.
Sample Input
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
Sample Output
Case #1: 2
Case #2: 3
找了半天错结果是 ++cnt 写成了 cnt++.
#include<iostream>
#include<cstring>
#include<cmath>
#include<cstdio>
#include<queue>
#define N 1000005
#define INF 0x3f3f3f3f
using namespace std;
int cnt;
int lay[N]; //层数
int head[N]; //结点连接的一条边
int dis[N]; //记录最短距离
bool inq[N];
struct edge{
int v,w,next; // 目标 权重 下一个
}edge[N];
queue<int> q;
void Addedge(int u,int v,int w){
edge[++cnt].v=v;
edge[cnt].w=w;
edge[cnt].next=head[u];
head[u]=cnt;
}
void Initial(){
memset(lay,-1,sizeof(lay));
memset(head,-1,sizeof(head));
cnt=0;
memset(dis,INF,sizeof(dis));
memset(inq,0,sizeof(inq));
}
void SPFA(){
int x=1;
q.push(x);
inq[x]=1;
dis[x]=0;
while(q.size())
{
x=q.front();
q.pop();
inq[x]=0;
for(int i=head[x];i!=-1;i=edge[i].next){
int w=edge[i].w,v=edge[i].v;
if( dis[v]> dis[x]+ w){
dis[v]= dis[x]+w;
if(!inq[v]){
q.push(v);
inq[v]=1;
}
}
}
}
}
int main()
{
int t;
scanf("%d",&t);
for(int tt=1;tt<=t;tt++){
Initial();
int n,m,c;
scanf("%d %d %d",&n,&m,&c);
for(int i=1;i<=n;i++){
scanf("%d",&lay[i]);
}
for(int i=1;i<=n;i++){
Addedge(n+lay[i],i,0);
if(lay[i]>1)
Addedge(i,n+lay[i]-1,c);
if(lay[i]<n)
Addedge(i,n+lay[i]+1,c);
}
for(int i=1;i<=m;i++){
int u,v,w;
scanf("%d %d %d",&u,&v,&w);
Addedge(u,v,w);
Addedge(v,u,w);
}
//建图完成
SPFA();
if(dis[n]==INF) dis[n]=-1;
printf("Case #%d: %d\n",tt,dis[n]);
}
return 0;
}