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
题意:有n个点,每个点在a[i] 层,该点可以到达在a[i] - 1和 a[i] + 1层的点 花费C,然后给出m条边
题解:注意 1. 在同一层的点 距离是不为0的,2.如果 上层和下层没有点也是不能到达的
所以点与层之间建边不能建双向边,因此我们可以建点与层之间的单向边,例如:x点在第k层,建第k层指向x的边,x点指向第k-1和k+1层,这样就可以避免1 2所说的情况了
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int N=2*1e5+10;
struct node{
int to,nex,d;
}e[N*4];
struct node1{
int id,d;
node1(){}
node1(int id_,int d_):id(id_),d(d_){}
bool operator <(const node1 &x)const
{
return d>x.d;
}
};
int n,m,w;
int head[N],dis[N],vis[N],len,in[N];
void init()
{
len=0;
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
}
void add(int u,int v,int w)
{
e[len].to=v;
e[len].d=w;
e[len].nex=head[u];
head[u]=len++;
}
int DIJ(int s,int t)
{
memset(dis,INF,sizeof(dis));
memset(vis,0,sizeof(vis));
priority_queue<node1> q;
node1 now,tmp;
int u,to;
q.push(node1(s,0));
dis[s]=0;
while(!q.empty())
{
now=q.top();q.pop();
if(vis[now.id]) continue;
vis[now.id]=1;
u=now.id;
for(int i=head[u];i!=-1;i=e[i].nex)
{
to=e[i].to;
if(!vis[to]&&dis[to]>dis[u]+e[i].d)
{
dis[to]=dis[u]+e[i].d;
q.push(node1(to,dis[to]));
}
}
}
if(dis[n]==INF) return -1;
return dis[n];
}
int main()
{
int T,nn=1,x,y,z;
scanf("%d",&T);
while(T--)
{
init();
scanf("%d%d%d",&n,&m,&w);
for(int i=1;i<=n;i++)
{
scanf("%d",&x);
add(n+x,i,0);
in[x]=1;
if(x>1) add(i,n+x-1,w);
if(x<n) add(i,n+x+1,w);
}
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
add(y,x,z);
add(x,y,z);
}
printf("Case #%d: %d\n",nn++,DIJ(1,n));
}
return 0;
}