标签:span har ati logs strong origin clu algorithm printf
5
20
16
10
10
4
5
2 3
3 4
3 5
4 5
1 5
Sample Output
8
5
5
-1
10
这道题就是一个可并堆+并查集裸题。可并堆很好写,但如何结合并查集,着实让我苦思了很久。实在没有办法,最开始只有用数组下标,但这样很明显是不符合套路的。
后来发现,结点可以加id。这样就可以就合并查集了。
但最后,发现可并堆+并查集可以合为一体。
代码如下(注释为+id版本):
1 #include <cstdio> 2 #include <algorithm> 3 template<class T>inline void readin(T &res) { 4 static char ch;T f=1; 5 while((ch=getchar())<‘0‘||ch>‘9‘)if(ch==‘-‘)f=-1; 6 res=ch-48;while((ch=getchar())>=‘0‘&&ch<=‘9‘)res=(res<<1)+(res<<3)+ch-48;res*=f; 7 } 8 const int N = 100005; 9 struct Node { 10 int key, dist;//, id; 11 Node *ls, *rs; 12 Node *fa; 13 }pool[N], *null=pool, *tnode[N]; 14 inline Node *find(Node *x) { 15 if(x->fa==x) return x; 16 return x->fa=find(x->fa); 17 } 18 /*int fa[N]; 19 inline int find(int x) { 20 if(fa[x]==x) return x; 21 return fa[x]=find(fa[x]); 22 }*/ 23 Node *merge(Node *a,Node *b) { 24 if(a==null) return b; 25 if(b==null) return a; 26 if(b->key>a->key) std::swap(a,b); 27 a->rs=merge(a->rs,b); 28 a->rs->fa=a; 29 //fa[a->rs->id]=a->id; 30 if(a->rs->dist>a->ls->dist) std::swap(a->ls,a->rs); 31 if(a->rs==null) a->dist=0; 32 else a->dist=a->rs->dist+1; 33 return a; 34 } 35 Node *pop(Node *nd) { 36 Node *l=nd->ls, *r=nd->rs; 37 l->fa=l;r->fa=r; 38 //fa[l->id]=l->id; 39 //fa[r->id]=r->id; 40 nd->ls=nd->rs=null;nd->dist=0; 41 return merge(l,r); 42 } 43 int main() { 44 int n, q, x, y; 45 null->ls=null->rs=null; 46 while(~scanf("%d",&n)) { 47 for( int i = 1; i <= n; i++ ) { 48 tnode[i]=&pool[i]; 49 readin(tnode[i]->key);//tnode[i]->id=i; 50 tnode[i]->ls=tnode[i]->rs=null;tnode[i]->dist=0; 51 tnode[i]->fa=tnode[i]; 52 //fa[i]=i; 53 } 54 readin(q); 55 while(q--) { 56 readin(x);readin(y); 57 if(find(tnode[x])==find(tnode[y])) printf("-1\n"); 58 //if(find(x)==find(y)) printf("-1\n"); 59 else { 60 Node *ra = tnode[x]->fa, *rb = tnode[y]->fa; 61 //Node *ra = tnode[fa[x]], *rb = tnode[fa[y]]; 62 Node *ta = pop(ra); 63 ra->key /= 2; 64 ra = merge(ta,ra); 65 Node *tb = pop(rb); 66 rb->key /= 2; 67 rb = merge(tb,rb); 68 printf("%d\n",merge(ra,rb)->key); 69 } 70 } 71 } 72 return 0; 73 }
标签:span har ati logs strong origin clu algorithm printf
原文地址:http://www.cnblogs.com/Doggu/p/hdu1512.html