hdoj 4725 The Shortest Path in Nya Graph

来源:互联网 发布:mp4制作软件 编辑:程序博客网 时间:2024/05/16 07:11

题目链接:The Shortest Path in Nya Graph

题目大意:有n个点,m条边,n层,每一层可以有多个点,接下来给每个点所在的层数,相邻层之间的点到另一层的花费为C,然后给出m条额外的边,问从1到n这个点的最短路

题目思路:明显的拆点的最短路,我们把每一层拆点成两个点n+i*2和n+i*2-1,然后做一遍最短路就好了

#include <cstdio>#include <cstring>#include <cstdlib>#include <algorithm>#include <cmath>#include <queue>using namespace std;typedef long long ll;const int maxn = 3e5+10;const int inf = 0x3f3f3f3f;int cnt, head[maxn];ll dis[maxn];struct Edge {    int v, next; ll w;    bool operator < (const Edge &rhs) const {        return w > rhs.w;    }} e[maxn*4];void add(int u,int v,int co){    e[cnt].v = v;    e[cnt].w = co;    e[cnt].next = head[u];    head[u] = cnt++;}void init() {    cnt = 0;    memset(head, -1, sizeof(head));}void dij(int s, int len) {    priority_queue<Edge> pq;    for (int i = 1; i <= len; i++)        dis[i] = inf;    bool vis[maxn] = {0};    dis[s] = 0;    pq.push((Edge){s, 0, 0});    while (!pq.empty()) {        Edge tmp = pq.top(); pq.pop();        if (vis[tmp.v]) continue;        vis[tmp.v] = 1;        for (int i = head[tmp.v]; ~i; i = e[i].next) {            Edge u = e[i];            if (dis[u.v] > dis[tmp.v] + u.w) {                dis[u.v] = dis[tmp.v] + u.w;                pq.push((Edge){u.v, 0, dis[u.v]});            }        }    }}int main(){    int t,n,m,c,x;    scanf("%d",&t);    for(int Case = 1;Case <= t;Case++){        init();        scanf("%d%d%d",&n,&m,&c);        for(int i = 1;i <= n-1;i++){            add(n+i*2-1,n+(i+1)*2,c);            add(n+(i+1)*2-1,n+i*2,c);        }        for(int i = 1;i <= n;i++){            scanf("%d",&x);            add(i,n+x*2-1,0);            add(n+x*2,i,0);        }        while(m--){            int uu,vv,ww;            scanf("%d%d%d",&uu,&vv,&ww);            add(uu,vv,ww);            add(vv,uu,ww);        }        dij(1,n*3);        if(dis[n] == inf) dis[n] = -1;        printf("Case #%d: %d\n",Case,dis[n]);    }    return 0;}
原创粉丝点击