【BZOJ1050】【枚举+并查集】旅行comf

【样例输入1】
4 2
1 2 1
3 4 2
1 4
【样例输入2】
3 3
1 2 10
1 2 5
2 3 8
1 3
【样例输入3】
3 2
1 2 2
2 3 4
1 3

【样例输出1】
IMPOSSIBLE
【样例输出2】
5/4
【样例输出3】
2

HINT

【数据范围】

1<  N < = 500

1 < = x, y < = N，0 < v < 30000，x ≠ y

0 < M < =5000

Source

【分析】

 1 #include <iostream>
2 #include <cstdio>
3 #include <algorithm>
4 #include <cstring>
5 #include <vector>
6 #include <utility>
7 #include <iomanip>
8 #include <string>
9 #include <cmath>
10 #include <queue>
11 #include <map>
12
13 const int MAXN = 500 + 10;
14 const int MAXM = 5000 + 10;
15 using namespace std;
16 struct EDGE{
17        int u, v ,w;
18        bool operator < (EDGE B)const{
19             return w < B.w;
20        }
21 }edge[MAXM];
22 int n, m, parent[MAXN];
23 int s, t;
24
25 int find(int x){return parent[x] < 0 ? x:parent[x] = find(parent[x]);}
26 void merge(int x, int y){
27      if (parent[x] > parent[y]){
28         parent[y] += parent[x];
29         parent[x] = y;
30      }else{
31         parent[x] += parent[y];
32         parent[y] = x;
33      }
34 }
35 void init(){
36      scanf("%d%d", &n, &m);
37      memset(parent, -1, sizeof(parent));
38      for (int i = 1; i <= m; i++){
39          scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w);
40      }
41      scanf("%d%d", &s, &t);
42      sort(edge + 1, edge + 1 + m);
43 }
44 int gcd(int a, int b){return b == 0? a:gcd(b, a % b);}
45 void work(){
46      int A = 30000, B = 1;
47      //枚举边长最小的边
48      for (int i = 1; i <= m; i++){
49          memset(parent, -1, sizeof(parent));
50          int j;
51          for (j = i; j <= m; j++){
52              int u = edge[j].u, v = edge[j].v;
53              u = find(u); v = find(v);
54              if (u != v) merge(u, v);
55              if (find(s) == find(t)) break;
56          }
57          if (j <= m){
58             if (edge[i].w * A > edge[j].w * B){
59                A = edge[j].w;
60                B = edge[i].w;
61             }
62          }
63      }
64      if (A == 30000 && B == 1) {printf("IMPOSSIBLE\n");return;}
65      if (A % B == 0) printf("%d\n", A / B);
66      else printf("%d/%d", A / gcd(A, B), B / gcd(A, B));
67 }
68
69 int main(){
70     int T;
71     #ifdef LOCAL
72     freopen("data.txt",  "r",  stdin);
73     freopen("out.txt",  "w",  stdout);
74     #endif
75     init();
76     work();
77     return 0;
78 }
View Code

posted @ 2015-03-08 19:47  TCtower  阅读(56)  评论(0编辑  收藏