HDU 6386 Age of Moyu

题目:Age of Moyu

思路:裸的堆优化dijkstra

代码:

#include<bits/stdc++.h>
using namespace std;

#define maxn 200000
#define inf (1LL<<40)
#define LL long long

struct Pair{
    LL y,z,col;
    Pair(){}
    Pair(LL yy,LL zz,LL c=0) {
        y=yy,z=zz,col=c;
    }
    bool operator < (const Pair oth) const {
        return z>oth.z;
    }
};

LL n,m;
vector<Pair> a[maxn+5];
bool Use[maxn+5]={0};

void readin() {
    for(LL i=1;i<=m;i++) {
        LL x,y,z;
        scanf("%lld%lld%lld",&x,&y,&z);
        a[x].push_back(Pair(y,z));
        a[y].push_back(Pair(x,z));
    }
}

void init() {
    for(LL i=1;i<=n;i++) a[i].clear();
}

LL dijkstra(){
    LL dist[maxn+5];
    for(LL i=1;i<=n;i++) dist[i]=inf;
    dist[1]=0;
    Use[1]=0;
    priority_queue<Pair> que;
    que.push(Pair(1,0));
    while(!que.empty()) {
        Pair h=que.top();
        que.pop();
        if(Use[h.y]) continue;
        for(LL i=0;i<a[h.y].size();i++){
            Pair x=a[h.y][i];
            if((h.col!=x.z)+h.z<dist[x.y]) {
                dist[x.y]=(h.col!=x.z)+h.z;
                que.push(Pair(x.y,dist[x.y],x.z));
            }
        }
    }
    return dist[n];
}

int main() {
    while(~scanf("%lld%d",&n,&m)) {
        init();
        readin();
        LL ans=dijkstra();
        if(ans==inf) ans=-1;
        printf("%lld\n",ans);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/rabbit_ZAR/article/details/81669643