USACO Section 2.4: Bessie Come Home

因为题目给了边的信息,所以比较适用bell-man的方法

 1 /*

 2 ID: yingzho1

 3 LANG: C++

 4 TASK: comehome

 5 */

 6 #include <iostream>

 7 #include <fstream>

 8 #include <string>

 9 #include <map>

10 #include <vector>

11 #include <set>

12 #include <algorithm>

13 #include <stdio.h>

14 #include <queue>

15 #include <cstring>

16 #include <cmath>

17 #include <list>

18 

19 using namespace std;

20 #define inf 10000000

21 

22 ifstream fin("comehome.in");

23 ofstream fout("comehome.out");

24 

25 int N;

26 struct edge {

27     char s, d;

28     int e;

29     edge(int a, int b, int c) : s(a), d(b), e(c) { }

30     edge() : s(0), d(0), e(0) { }

31 };

32 map<char, int> dis;

33 int edgenum = 0;

34 

35 int main()

36 {

37     fin >> N;

38     vector<edge> path(2*N);

39 

40     for (int i = 0; i < N; i++) {

41         char s, d;

42         int e;

43         fin >> s >> d >> e;

44         path[edgenum].s = s;

45         path[edgenum].d = d;

46         path[edgenum++].e = e;

47         path[edgenum].s = d;

48         path[edgenum].d = s;

49         path[edgenum++].e = e;

50     }

51     //for (int i = 0; i < edgenum; i++) {

52         //cout << "s: " << path[i].s << ", d: " << path[i].d << ", e: " << path[i].e << endl;

53     //}

54     for (char i = 'a'; i <= 'z'; i++) dis[i] = inf;

55     for (char i = 'A'; i <= 'Z'; i++) dis[i] = inf;

56     dis['Z'] = 0;

57     bool flag;

58     for (int i = 0; i < edgenum; i++) {

59         flag = false;

60         for (int j = 0; j < edgenum; j++) {

61             if (dis[path[j].d] > dis[path[j].s]+path[j].e) {

62                 dis[path[j].d] = dis[path[j].s]+path[j].e;

63                 flag = true;

64                 //cout << "dis[" << path[j].d << "]: " << dis[path[j].d] << endl;

65             }

66         }

67         if (!flag) break;

68     }

69     int min_path = inf;

70     char min_index;

71     for (int i = 0; i < edgenum; i++) {

72         if (path[i].s >= 'A' && path[i].s < 'Z' && min_path > dis[path[i].s]) {

73             min_path = min(min_path, dis[path[i].s]);

74             //cout << path[i].s << "'s dis: " << dis[path[i].s] << endl;

75             min_index = path[i].s;

76         }

77     }

78     fout <<  min_index << " " << min_path << endl;

79 

80     return 0;

81 }

 

你可能感兴趣的:(USACO)