【USACO06NOV】路障

【题目链接】

          点击打开链接

【算法】

         最短路

【代码】

           

#include
using namespace std;
#define MAXN 5000
#define MAXM 100000

int i,N,M,shortest,ans;
int dista[MAXN+10],distb[MAXN+10],x[MAXM+10],y[MAXM+10],d[MAXM+10],
        visa[MAXN+10],visb[MAXN+10];
vectorint,int> > E[MAXN+10];
 
template  void read(T &x) {
        int f=1; char c = getchar(); x=0;
        for (; !isdigit(c); c = getchar()) { if (c=='-') f=-1; }
        for (; isdigit(c); c = getchar()) x=x*10+c-'0';
        x*=f;
}

inline void dijkstra1() {
        int i,x,to;
        priority_queueint,int> > q;
        for (i = 2; i <= N; i++) dista[i] = 2e9;
        q.push(make_pair(-0,1));
        while (!q.empty()) {
                x = q.top().second; q.pop();
                if (visa[x]) continue;
                visa[x] = 1;
                for (i = 0; i < E[x].size(); i++) {
                        to = E[x][i].first;
                        if (dista[x] + E[x][i].second < dista[to]) {
                                dista[to] = dista[x] + E[x][i].second;
                                q.push(make_pair(-dista[to],to));
                        }
                }
        }
}

inline void dijkstra2() {
        int i,x,to;
        priority_queueint,int> > q;
        for (i = 1; i < N; i++) distb[i] = 2e9;
        q.push(make_pair(-0,N));
        while (!q.empty()) {
                x = q.top().second; q.pop();
                if (visb[x]) continue;
                visb[x] = 1;
                for (i = 0; i < E[x].size(); i++) {
                        to = E[x][i].first;
                        if (distb[x] + E[x][i].second < distb[to]) {
                                distb[to] = distb[x] + E[x][i].second;
                                q.push(make_pair(-distb[to],to));
                        }
                }
        }
} 

int main() {
        
        read(N); read(M);
        
        for (i = 1; i <= M; i++) {
                read(x[i]); read(y[i]); read(d[i]);
                E[x[i]].push_back(make_pair(y[i],d[i]));
                E[y[i]].push_back(make_pair(x[i],d[i]));    
        }
        
        dijkstra1();
        dijkstra2();
        
        shortest = dista[N];
        ans = 2e9;
        
        for (i = 1; i <= M; i++) {
                if (dista[x[i]] + d[i] + distb[y[i]] > shortest)
                        ans = min(ans,dista[x[i]]+d[i]+distb[y[i]]);    
                if (dista[y[i]] + d[i] + distb[x[i]] > shortest)
                        ans = min(ans,dista[y[i]]+d[i]+distb[x[i]]);    
        }
        
        cout<< ans << endl;
        
        return 0;
    
}

 

转载于:https://www.cnblogs.com/evenbao/p/9196395.html

你可能感兴趣的:(【USACO06NOV】路障)