Monkey King
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6586 Accepted Submission(s): 2821
Problem Description
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.
Input
There are several test cases, and each case consists of two parts.
First part: The first line contains an integer N(N<=100,000), which indicates the number of monkeys. And then N lines follows. There is one number on each line, indicating the strongness value of ith monkey(<=32768).
Second part: The first line contains an integer M(M<=100,000), which indicates there are M conflicts happened. And then M lines follows, each line of which contains two integers x and y, indicating that there is a conflict between the Xth monkey and Yth.
Output
For each of the conflict, output -1 if the two monkeys know each other, otherwise output the strongness value of the strongest monkey in all friends of them after the duel.
Sample Input
5
20
16
10
10
4
5
2 3
3 4
3 5
4 5
1 5
Sample Output
8
5
5
-1
10
题目链接:HDU 1512
显然题目主要难点就是如何快速得到一个集合的最大值,合并我们用并查集,但是堆怎么合并呢?此处就用$pd\_ds$库的优先队列来合并,就可以少写很多代码了。一开始把$!empty$写成$empty$怀疑了一会儿人生1
A.join(B)//将B合并到A的堆里,同时清空堆B
代码:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
using namespace std;
using namespace __gnu_pbds;
const int N = 100010;
__gnu_pbds::priority_queue<int, less<int>, pairing_heap_tag> Q[N];
namespace dsu
{
int pre[N];
void init()
{
for (int i = 0; i < N; ++i)
{
pre[i] = -1;
if (!Q[i].empty())
Q[i].clear();
}
}
int Find(int n)
{
return pre[n] == -1 ? n : pre[n] = Find(pre[n]);
}
}
int arr[N];
int main(void)
{
int n, m, a, b, i;
while (~scanf("%d", &n))
{
dsu::init();
for (i = 1; i <= n; ++i)
{
scanf("%d", &arr[i]);
Q[i].push(arr[i]);
}
scanf("%d", &m);
while (m--)
{
scanf("%d%d", &a, &b);
int fa = dsu::Find(a), fb = dsu::Find(b);
if (fa == fb)
puts("-1");
else
{
int A = Q[fa].top(), B = Q[fb].top();
Q[fa].pop();
Q[fa].push(A >> 1);
Q[fb].pop();
Q[fb].push(B >> 1);
Q[fa].join(Q[fb]);
dsu::pre[fb] = fa;
printf("%d\n", Q[fa].top());
}
}
}
return 0;
}