[USACO06NOV]Roadblocks G 嚴格次短路徑

#include<bits/stdc++.h>
using namespace std;
#define ll long long
typedef pair<int,int>pii;
const int maxn= 1e4+7;
#define INF 0x3f3f3f3f
int fir[maxn],sec[maxn];
bool vis[maxn];
int n,r;
vector<pii>g[maxn];
void spfa()
{
    memset(fir,0x3f,sizeof(fir));
    memset(sec,0x3f,sizeof(sec));
    fir[1]=0;
    queue<int>q;
    q.push(1);
    vis[1]=1;
    while(!q.empty())
    {
        int t=q.front();
        q.pop();
        vis[t]=0;
        for(auto xx:g[t])
        {
            int y=xx.first,v=xx.second;
            // cout<<"*"<<t<<" "<<fir[t]<<" "<<sec[t]<<endl;
            // cout<<y<<" "<<fir[y]<<" "<<sec[y]<<endl;
            if(fir[y]>fir[t]+v)
            {
                sec[y]=fir[y];
                fir[y]=fir[t]+v;
                if(sec[t]+v<sec[y])sec[y]=sec[t]+v;
                if(!vis[y])
                {
                    q.push(y);
                    vis[y]=1;
                    // cout<<"&"<<endl;
                }
            }
            else if(fir[t]+v>fir[y]&&fir[t]+v<sec[y])
            {
                sec[y]=fir[t]+v;
                if(!vis[y])
                {
                    q.push(y);
                    vis[y]=1;
                    // cout<<"&&"<<endl;
                }
            }
            else if(sec[t]+v<sec[y])
            {
                sec[y]=sec[t]+v;
                if(!vis[y])
                {
                    q.push(y);
                    vis[y]=1;
                    // cout<<"&&&"<<endl;
                }
            }
        }
    }
}
int main()
{
    while(cin>>n>>r)
    {
        for(int i=0;i<r;i++)
        {
            int x,y,z;
            cin>>x>>y>>z;
            g[x].push_back(make_pair(y,z));
            g[y].push_back(make_pair(x,z));
        }
        // cout<<"((("<<endl
        spfa();
        cout<<sec[n]<<endl;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章