bzoj 1455 可并堆+并查集

 

一个堆和一个并查集对应,并且满足并查集中所有没有死的人等于堆中的人

 

 1 /**************************************************************
 2     Problem: 1455
 3     User: idy002
 4     Language: C++
 5     Result: Accepted
 6     Time:2688 ms
 7     Memory:32336 kb
 8 ****************************************************************/
 9  
10 #include <cstdio>
11 #define N 1000010
12  
13 struct Node {
14     int u, w, s;
15     Node *ls, *rs;
16     void update() {
17         s = 1;
18         if( ls ) s += ls->s;
19         if( rs ) s += rs->s;
20     }
21 }pool[N], *tail=pool, *root[N];
22  
23 int n, m;
24 int fat[N], die[N];
25  
26 int find( int a ) {
27     return a==fat[a] ? a : fat[a]=find(fat[a]);
28 }
29 Node *newnode( int u, int w ) {
30     Node *nd = ++tail;
31     nd->u = u;
32     nd->w = w;
33     nd->ls = nd->rs = 0;
34     return nd;
35 }
36 Node *smerge( Node *na, Node *nb ) {
37     if( !na && !nb ) return 0;
38     if( !na ) return nb;
39     if( !nb ) return na;
40     if( na->w < nb->w ) {
41         na->rs = smerge( na->rs, nb );
42         na->update();
43         return na;
44     } else {
45         nb->rs = smerge( nb->rs, na );
46         nb->update();
47         return nb;
48     }
49 }
50 int main() {
51     scanf( "%d", &n );
52     for( int i=1,w; i<=n; i++ ) {
53         scanf( "%d", &w );
54         root[i] = newnode(i,w);
55         fat[i] = i;
56     }
57     scanf( "%d", &m );
58     for( int i=1,u,v; i<=m; i++ ) {
59         char ch[10];
60         scanf( "%s", ch );
61         if( ch[0]=='M' ) {
62             scanf( "%d%d", &u, &v );
63             if( die[u] || die[v] ) continue;
64             int fu = find(u);
65             int fv = find(v);
66             if( fu==fv ) continue;
67             fat[fu] = fv;
68             root[fv] = smerge( root[fu], root[fv] );
69         } else {
70             scanf( "%d", &u );
71             if( die[u] ) {
72                 printf( "0\n" );
73                 continue;
74             }
75             int fu = find(u);
76             int v = root[fu]->u;
77             printf( "%d\n", root[fu]->w );
78             die[v] = true;
79             root[fu] = smerge( root[fu]->ls, root[fu]->rs );
80         }
81     }
82 }
View Code

 

posted @ 2015-06-12 19:13  idy002  阅读(109)  评论(0编辑  收藏  举报