# [BZOJ] 1631: [Usaco2007 Feb]Cow Party

## 1631: [Usaco2007 Feb]Cow Party

Time Limit: 5 Sec  Memory Limit: 64 MB
Submit: 866  Solved: 624
[Submit][Status][Discuss]

## Description

农场有N(1≤N≤1000)个牛棚，每个牛棚都有1只奶牛要参加在X牛棚举行的奶牛派对．共有M(1≤M≤100000)条单向路连接着牛棚，第i条踣需要Ti的时间来通过．牛们都很懒，所以不管是前去X牛棚参加派对还是返回住所，她们都采用了用时最少的路线．那么，用时最多的奶牛需要多少时间来回呢？

## Input

第2行到第M+1行,每行三个用空格隔开的整数:Ai, Bi,以及Ti.表示一条道路的起点,终点和需要花费的时间.

4 8 2
1 2 4
1 3 2
1 4 7
2 1 1
2 3 5
3 1 2
3 4 4
4 2 3

10

Silver

## Code

 1 #include<cstdio>
2 #include<iostream>
3 #include<cstring>
4 #include<queue>
5 #define maxn 1000000
6 using namespace std;
7
8 struct edge{
9     int from,v,len;
10 }e[maxn],e1[maxn];
11
12 const int inf = 0x3f3f3f3f;
13 bool book[maxn];
14 int tot,tot1,first[maxn],first1[maxn],n,m,a,b,c,x,dis[maxn],dis1[maxn];
15 void insert(int u,int v,int len){
16     tot++;
17     e[tot].from = first[u];
18     e[tot].v = v;
19     e[tot].len = len;
20     first[u] = tot;
21
22     tot1++;
23     e1[tot1].from = first1[v];
24     e1[tot1].v = u;
25     e1[tot1].len = len;
26     first1[v] = tot;
27 }
28
29 void SPFA(){
30     memset(book,false,sizeof(book));
31     for(int i = 1;i <= n;i++) dis[i] = inf;
32
33     queue<int> Q;
34     Q.push(x);
35     book[x] = true;
36     dis[x] = 0;
37
38     while(!Q.empty()){
39         int p = Q.front();
40         Q.pop();
41
42         for(int i = first[p];i;i = e[i].from){
43             int v = e[i].v;
44             if(dis[v] > dis[p]+e[i].len){
45                 dis[v] = dis[p]+e[i].len;
46                 if(!book[v]){
47                     book[v] = true;
48                     Q.push(v);
49                 }
50             }
51         }
52         book[p] = false;
53     }
54
55     for(int i = 1;i <= n;i++) dis1[i] = inf;
56     Q.push(x);
57     dis1[x] = 0;
58     book[x] = true;
59
60     while(!Q.empty()){
61         int p = Q.front();
62         Q.pop();
63
64         for(int i = first1[p];i;i = e1[i].from){
65             int v = e1[i].v;
66             if(dis1[v] > dis1[p]+e1[i].len){
67                 dis1[v] = dis1[p]+e1[i].len;
68                 if(!book[v]){
69                     book[v] = true;
70                     Q.push(v);
71                 }
72             }
73         }
74         book[p] = false;
75     }
76
77     int maxx = 0;
78     for(int i = 1;i <= n;i++){
79         maxx = max(maxx,dis[i]+dis1[i]);
80     }
81
82     printf("%d",maxx);
83 }
84
85 int main(){
86     scanf("%d%d%d",&n,&m,&x);
87
88     for(int i = 1;i <= m;i++){
89         scanf("%d%d%d",&a,&b,&c);
90         insert(a,b,c);
91     }
92
93     SPFA();
94
95     return 0;
96 } 
SPFA ver

posted @ 2017-09-02 22:54  Leviaton  阅读(126)  评论(0编辑  收藏  举报