lightoj 1009 - Back to Underworld 【DFS】

本博客探讨如何通过收集战斗记录数据,利用DFS算法找出两种不同种族中人数最多的可能值,适用于大规模数据集的高效处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:lightoj 1009 - Back to Underworld

1009 - Back to Underworld
PDF (English) Statistics Forum
Time Limit: 4 second(s) Memory Limit: 32 MB
The Vampires and Lykans are fighting each other to death. The war has become so fierce that, none knows who will win. The humans want to know who will survive finally. But humans are afraid of going to the battlefield.

So, they made a plan. They collected the information from the newspapers of Vampires and Lykans. They found the information about all the dual fights. Dual fight means a fight between a Lykan and a Vampire. They know the name of the dual fighters, but don’t know which one of them is a Vampire or a Lykan.

So, the humans listed all the rivals. They want to find the maximum possible number of Vampires or Lykans.

Input
Input starts with an integer T (≤ 10), denoting the number of test cases.

Each case contains an integer n (1 ≤ n ≤ 105), denoting the number of dual fights. Each of the next n lines will contain two different integers u v (1 ≤ u, v ≤ 20000) denoting there was a fight between u and v. No rival will be reported more than once.

Output
For each case, print the case number and the maximum possible members of any race.

Sample Input
Output for Sample Input
2
2
1 2
2 3
3
1 2
2 3
4 2
Case 1: 2
Case 2: 3
Note
Dataset is huge, use faster I/O methods.

PROBLEM SETTER: JANE ALAM JAN

题意:有n个战争,每个战争的双方分别属于种族1和种族2。问你种族1和种族2之间最多的人数。

思路:对于一个连通图,显然确定一个点,那么整个图就都确定了。那么直接DFS每个连通图就好了。

AC代码:

#include <cstdio>
#include <cstring>
#include <vector>
#define CLR(a, b) memset(a, (b), sizeof(a))
using namespace std;
bool vis[20010], use[20010];
vector<int> G[20010];
int sum1, sum;
void DFS(int u, bool flag) {
    sum++; if(flag == 1) sum1++;
    vis[u] = true;
    for(int i = 0; i < G[u].size(); i++) {
        int v = G[u][i];
        if(vis[v]) continue;
        DFS(v, !flag);
    }
}
int main()
{
    int t, kcase = 1;
    scanf("%d", &t);
    while(t--) {
        int n; scanf("%d", &n);
        for(int i = 1; i <= 20000; i++) {
            vis[i] = use[i] = false;
            G[i].clear();
        }
        int Max = 0;
        for(int i = 1; i <= n; i++) {
            int u, v; scanf("%d%d", &u, &v);
            use[u] = use[v] = true;
            G[u].push_back(v);
            G[v].push_back(u);
            Max = max(Max, u);
            Max = max(Max, v);
        }
        int ans = 0;
        for(int i = 1; i <= Max; i++) {
            if(!use[i]) continue; if(vis[i]) continue;
            sum1 = sum = 0; DFS(i, 0);
            ans += max(sum1, sum - sum1);
        }
        printf("Case %d: %d\n", kcase++, ans);
    }
    return 0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值