码迷,mamicode.com
首页 > 其他好文 > 详细

hdu_1512 Monkey King

时间:2017-11-25 15:18:35      阅读:119      评论:0      收藏:0      [点我收藏+]

标签:his   wap   ges   space   ==   nal   eve   merge   friends   

题目:

  Once in a forest, there lived N aggressive monkeys. At the beginning, they each does things in its own way and none of them knows each other. But monkeys can‘t avoid quarrelling, and it only happens between two monkeys who does not know each other. And when it happens, both the two monkeys will invite the strongest friend of them, and duel. Of course, after the duel, the two monkeys and all of there friends knows each other, and the quarrel above will no longer happens between these monkeys even if they have ever conflicted.
  Assume that every money has a strongness value, which will be reduced to only half of the original after a duel(that is, 10 will be reduced to 5 and 5 will be reduced to 2).
  And we also assume that every monkey knows himself. That is, when he is the strongest one in all of his friends, he himself will go to duel.

思路:

  题目要求求一群猴子中的最大值,又要合并两群猴子。就可以用并查集和可并堆实现。。。

代码:

#include <bits/stdc++.h>
#define MAXN 100005
#define dis(a) ((a)?a->d:-1)
#define pop(a) a=merge(a->lson,a->rson)
#define check(a,b) (find(a)==find(b))
using namespace std;
struct Node{
    int k,d;
    Node *lson,*rson;
    Node(int n=0){
        k=n;
        d=0;
        lson=rson=NULL;
    }
};
Node* merge(Node *&a,Node *&b){
    if(!a)
        return b;
    if(!b)
        return a;
    if(b->k>a->k)
        swap(a,b);
    a->rson=merge(a->rson,b);
    if(dis(a->rson)>dis(a->lson))
        swap(a->lson,a->rson);
    b=NULL;
    return a;
}
inline void push(Node *&a,int k){
Node *p=new Node(k);
    a=merge(a,p);
}
Node *heap[MAXN]={NULL};
int p[MAXN];
int find(int k){
    return k==p[k]?k:p[k]=find(p[k]);
}
int main(){
int n,m;
    ios::sync_with_stdio(false);
    cin.tie(0);
    while(cin>>n){
    	for(int i=1;i<=n;i++){
        	int a;
        	cin>>a;
        	heap[i]=new Node(a);
        	p[i]=i;
    	}
    	cin>>m;
    	while(m--){
        	int a,b;
        	cin>>a>>b;
        	if(check(a,b))
            	cout<<"-1"<<endl;
        	else {
            	int k1,k2;
            	k1=heap[find(a)]->k;
            	k2=heap[find(b)]->k;
            	pop(heap[find(a)]);
            	pop(heap[find(b)]);
            	push(heap[find(a)],k1/2);
            	push(heap[find(b)],k2/2);
            	heap[find(a)]=merge(heap[find(a)],heap[find(b)]);
            	p[find(b)]=find(a);
            	cout<<heap[find(a)]->k<<endl;
        	}
        }
        for(int i=1;i<=n;i++)
            delete heap[i];
    }
    return 0;
}

 

hdu_1512 Monkey King

标签:his   wap   ges   space   ==   nal   eve   merge   friends   

原文地址:http://www.cnblogs.com/HC-LittleJian/p/7895100.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!