当前位置: 首页 > 工具软件 > go-summer > 使用案例 >

SPOJ - IAPCR2F Summer Trip (并查集裸题)

柴飞星
2023-12-01


IAPCR2F - Summer Trip

no tags 

In this hot summer AIUB students decided to go on a trip to Cox’s Bazaar sea beach. Every student has some amount of money to spend in this trip. Each student belongs to some group. If student A knows student B, B knows C then A, B and C belong to the same group. In order to utilize the budget properly students hired a travel agency to get an optimal travel plan. They submitted the information about all the student’s money and relations among them. Now the agency wants to figure out the number of groups and the total budget of each group. Total budget of a group is the summation of all the student’s money in that group.

Input

The first line contains an integer T (1<=T<=50), denoting the number of test cases.

Each case starts with two integers N M. N (1<=N<=1000), denotes the number of students and M (0<=M<=(N*(N-1)/2)), denotes the number of relationships. In the next line N integers are given. The ith (1<=i<=N) integer ai (1<=ai<=100) denotes the money ith student has. Next M lines each contains two integers u v, (1<=u,v<=N and u != v) denoting that u knows v and vice versa.

Output

For each test case output “Case X: K” where X is the case number starting from 1 and K is the number of groups. In the next line output K integers, the total budget of all the groups in ascending order of budget.

Example

Input:
1
5 3
5 7 4 6 8
1 2
1 3
4 5

Output:
Case 1: 2
14 16
就是用并查集求出有几个集合,每个集合的值是多少,裸题。。我把sum[Find(x)] += sum[Find(y)]写成 sum[x] += sum[y] 了  wa哭了。。。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e3 + 5;
int n, m, pre[maxn], sum[maxn], sum2[maxn], book[maxn][maxn];
int Find(int x)
{
    return pre[x] == x ? x : pre[x] = Find(pre[x]);
}
void join(int x, int y)
{
    if(Find(y) != Find(x))
        sum[Find(x)] += sum[Find(y)];
    pre[Find(y)] = Find(x);

}
int main()
{
    int t, ca = 1;
    scanf("%d", &t);
    while(t--)
    {
//        memset(book, 0, sizeof(book));
        scanf("%d%d", &n, &m);
        for(int i = 1; i <= n; i++)
        {
            scanf("%d", &sum[i]);
            pre[i] = i;
        }
        int u, v;
        while(m--)
        {
            scanf("%d%d", &u, &v);
            join(u, v);
        }
        int ans = 0, index = 1;
        for(int i = 1; i <= n; i++)
            if(pre[i] == i)
                ans++, sum2[index++] = sum[i];
        printf("Case %d: %d\n", ca++, ans);
        sort(sum2+1,sum2+index);
        for(int i = 1; i <= ans; i++)
        {
            printf("%d%c", sum2[i], i == ans ? '\n' : ' ');
        }
    }
    return 0;
}



 类似资料: