题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4725
如果直接建图复杂度过大,但是考虑到每层之间的有效边很少,只要在每层增加两个虚拟节点n+i和2*n+i。n+i节点向 i 层的所有连边,权值为0。i 层的所有点向2*n+i节点连边,权值为0。然后每层直接建立边就可以了,即2*n+i-1向n+i连边,权值为c,2*n+i向n+i-1连边,权值为c。3*n个点,最多有有9*n条边。。
//STATUS:C++_AC_730MS_14340KB
#include <functional>
#include <algorithm>
#include <iostream>
//#include <ext/rope>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <numeric>
#include <cstring>
#include <cassert>
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <list>
#include <set>
#include <map>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,102400000")
//using namespace __gnu_cxx;
//define
#define pii pair<int,int>
#define mem(a,b) memset(a,b,sizeof(a))
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define PI acos(-1.0)
//typedef
typedef __int64 LL;
typedef unsigned __int64 ULL;
//const
const int N=;
const int INF=0x3f3f3f3f;
const int MOD=,STA=;
const LL LNF=1LL<<;
const double EPS=1e-;
const double OO=1e60;
const int dx[]={-,,,};
const int dy[]={,,,-};
const int day[]={,,,,,,,,,,,,};
//Daily Use ...
inline int sign(double x){return (x>EPS)-(x<-EPS);}
template<class T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
template<class T> inline T lcm(T a,T b,T d){return a/d*b;}
template<class T> inline T Min(T a,T b){return a<b?a:b;}
template<class T> inline T Max(T a,T b){return a>b?a:b;}
template<class T> inline T Min(T a,T b,T c){return min(min(a, b),c);}
template<class T> inline T Max(T a,T b,T c){return max(max(a, b),c);}
template<class T> inline T Min(T a,T b,T c,T d){return min(min(a, b),min(c,d));}
template<class T> inline T Max(T a,T b,T c,T d){return max(max(a, b),max(c,d));}
//End struct Edge{
int u,v,w;
}e[*N];
int first[N],next[*N];
LL d[N];
int S,T,n,m,c,mt; void adde(int a,int b,int c)
{
e[mt].u=a,e[mt].v=b;e[mt].w=c;
next[mt]=first[a],first[a]=mt++;
}
#define pli pair<LL,int>
LL dijkstra(int s)
{
int i,j,u,v,x;
pli t;
priority_queue<pli,vector<pli>,greater<pli> > q;
for(i=;i<=*n;i++)d[i]=LNF;
d[s]=;
q.push(make_pair(d[s],s));
while(!q.empty()){
t=q.top();q.pop();
u=t.second;
if(t.first!=d[u])continue;
for(i=first[u];i!=-;i=next[i]){
if(d[u]+e[i].w<d[e[i].v]){
d[e[i].v]=d[u]+e[i].w;
q.push(make_pair(d[e[i].v],e[i].v));
}
}
}
return d[T];
} int main(){
// freopen("in.txt","r",stdin);
int Ca,i,j,k,a,b,w,ca=;
scanf("%d",&Ca);
while(Ca--)
{
scanf("%d%d%d",&n,&m,&c);
S=,T=n;
mem(first,-);mt=;
for(i=;i<=n;i++){
scanf("%d",&a);
adde(n+a,i,);
adde(i,(n<<)+a,);
}
for(i=;i<=n;i++){
adde((n<<)+i-,n+i,c);
adde((n<<)+i,n+i-,c);
}
for(i=;i<m;i++){
scanf("%d%d%d",&a,&b,&w);
adde(a,b,w);
adde(b,a,w);
}
dijkstra(S);
if(d[T]==LNF)d[T]=-; printf("Case #%d: %I64d\n",ca++,d[T]);
}
return ;
}