BZOJ2753 SCOI2012day1T1滑雪与时间胶囊(bfs+kruskal)

 1 #include <queue>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cstdlib>
 5 #include <iostream>
 6 #include <algorithm>
 7 #define MaxN 100010
 8 #define MaxM 2000010
 9 #define LL long long 
10 using namespace std;
11 int S = 0, n, m;
12 int h[MaxN], head[MaxN], vis[MaxN], f[MaxN], q[MaxM];
13 struct rec{
14     int u, v, c, nxt;
15 }E[MaxM];
16 
17 void Bfs(){
18 //    memset(vis, 0, sizeof(vis));
19     int cl, op;
20     vis[1] = 1;
21     q[cl = op = 1] = 1;
22     while (cl <= op){
23         int u = q[cl];
24         for (int i = head[u]; i; i = E[i].nxt){
25             int v = E[i].v;
26             if (vis[v]) continue;
27             vis[v] = 1;
28             q[++op] = v;
29         }
30         cl++;
31     }
32 }
33 
34 bool cmp(rec a, rec b){
35     if (h[a.v] != h[b.v]) return h[a.v] > h[b.v];
36     return a.c < b.c;
37 } 
38 
39 int find(int x){
40     if (!f[x]) return x;
41     return f[x] = find(f[x]);
42 }
43 
44 LL Kruskal(){
45     int v, c, u, t1, t2;
46     LL t = 0ll;
47     sort(E+1, E+1+S, cmp);
48     for (int i = 1; i <= S; i++){
49         v = E[i].v, c = E[i].c, u = E[i].u;
50         if (!vis[v] || !vis[u]) continue;
51         t1 = find(u), t2 = find(v);
52         if (t1 == t2) continue;
53         f[t1] = t2;
54         t += (LL) c;
55     }
56     return t;
57 }
58 
59 void Solve(){
60     int ans = 0;
61 //    for (int j = 1; j <= n; j++)
62 //    for (int i = head[j]; i; i = E[i].nxt) cout<<E[i].u <<" "<<E[i].v<<" "<<E[i].c<<endl;
63     Bfs();
64     for (int i = 1; i <= n; i++) 
65         if (vis[i]) ans++;
66     cout<<ans <<" "<<Kruskal()<<endl;
67 }
68 
69 void adde(int u, int v, int c){
70     E[++S] = (rec) {u, v, c, head[u]};
71     head[u] = S;
72 }
73 
74 void Read_Data(){
75     scanf("%d%d", &n, &m);
76     memset(head, 0, sizeof(head));
77     for (int i = 1; i <= n; i++) scanf("%d", &h[i]);
78     for (int i = 1,u,v,c,t; i <= m; i++){
79         scanf("%d%d%d", &u, &v, &c);
80         if (h[v] > h[u]) t=u,u=v,v=t;
81         adde(u, v, c);
82         if (h[v] == h[u]) adde(v, u, c);
83     }
84 }
85 
86 int main(){
87     freopen("ski.in", "r", stdin);
88     freopen("ski.out", "w", stdout);
89     Read_Data();
90     Solve();
91     fclose(stdin);
92     fclose(stdout);    
93     return 0;
94 } 

 

posted @ 2015-12-29 18:17  Lukaluka  阅读(165)  评论(0编辑  收藏  举报