BZOJ 1631: [Usaco2007 Feb]Cow Party【最短路】

1631: [Usaco2007 Feb]Cow Party

【题目描述】
传送门

题解

正向建边,从X开始刷一趟SPFA,然后反向建边,从X刷一趟SPFA,最后两次的答案加和就可以了。

代码如下

#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int n,m,X,dst[2][100005],Ans;
int lnk[2][100005],Son[2][100005],Nxt[2][100005],W[2][100005],tot[2];
queue<int> que;
bool vis[100005];
void Add(int a,int x,int y,int z){Son[a][++tot[a]]=y;W[a][tot[a]]=z;Nxt[a][tot[a]]=lnk[a][x];lnk[a][x]=tot[a];}
void SPFA(int a){
    que.push(X);vis[X]=1;dst[a][X]=0;
    while(!que.empty()){
        int x=que.front();que.pop();vis[x]=0;
        for(int j=lnk[a][x];j;j=Nxt[a][j])
        if(dst[a][Son[a][j]]>dst[a][x]+W[a][j]){
            dst[a][Son[a][j]]=dst[a][x]+W[a][j];
            if(!vis[Son[a][j]]) vis[Son[a][j]]=1,que.push(Son[a][j]);
        }
    }
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("prob.in","r",stdin);
    freopen("prob.out","w",stdout);
    #endif
    memset(dst,63,sizeof(dst));
    scanf("%d%d%d",&n,&m,&X);
    for(int i=1;i<=m;i++){
        int x,y,z;scanf("%d%d%d",&x,&y,&z);
        Add(0,x,y,z);Add(1,y,x,z);
    }
    SPFA(0),SPFA(1);
    for(int i=1;i<=n;i++) Ans=max(Ans,dst[0][i]+dst[1][i]);
    printf("%d\n",Ans);
    return 0;
}
posted @ 2018-05-17 21:26  XSamsara  阅读(124)  评论(0编辑  收藏  举报