您的位置:首页 > 其它

The Shortest Path in Nya Graph HDU - 4725

2018-03-05 20:01 225 查看
题意:

层与层之间移动需耗费C
额外边cost 直接给出
坑题spfa 可过 但需将queue定义为全局 不然会TLE#include <bits/stdc++.h>

using namespace std;
const int MAX_V = 200005;
struct edge{
int v;
int cost;
int next;
};
struct edge es[20 * MAX_V];
int lay[MAX_V],d[MAX_V],head[MAX_V];
bool vv[MAX_V],inqueue[MAX_V];
int V,len;
deque<int> q;
void add(int from,int to,int val)
{
es[len].v=to;
es[len].cost =val;
es[len].next = head[from];
head[from]=len++;
}
void spfa(int s){
d[s] = 0; inqueue[s] = 1;
while(!q.empty()) q.pop_back();
q.push_back(s);
while (!q.empty()){
int u = q.front(); q.pop_front();
inqueue[u] = 0;
for (int i = head[u];i != -1;i = es[i].next){
int v = es[i].v;
if (d[v] > d[u] + es[i].cost){
d[v] = d[u] + es[i].cost;
if (!inqueue[v]){
if (!q.empty() && d[v] < d[q.front()])
q.push_front(v);
else
q.push_back(v);
inqueue[v] = 1;
}
}
}
}
}

void init(){
memset(head,-1,sizeof head);
memset(vv,0,sizeof vv);
memset(d,0x3f, sizeof(d));
}
int main()
{
int T;
scanf("%d",&T);
memset(inqueue,0,sizeof inqueue);
for (int cnt = 1;cnt<=T;cnt++){
init();
int M,W;
scanf("%d%d%d",&V,&M,&W);
len = 0;
for (int i = 1;i<=V;i++){
int t;
scanf("%d",&t);
lay[i] = t;
vv[t] = 1;
}
for (int i = 1;i<V;i++){
if (vv[i] && vv[i+1]){
add(V+i,V+i+1, W);
add(V+i+1,V+i, W);
}
}
for (int i = 1;i<=V;i++){
add(V+lay[i],i,0);
if(lay[i]>1) add(i,V+lay[i]-1,W);
if(lay[i]<V) add(i,V+lay[i]+1,W);
}
for (int i = 1;i<=M;i++){
int u,v,c;
scanf("%d%d%d",&u,&v,&c);
add(u,v,c);
add(v,u,c);
}
spfa(1);
printf("Case #%d: %d\n",cnt,d[V] < 0x3f3f3f3f ? d[V] : -1 );
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  acm spfa