hdu_1512 Monkey King
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu_1512 Monkey King相关的知识,希望对你有一定的参考价值。
题目:
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的主要内容,如果未能解决你的问题,请参考以下文章