fzu 2141 Sub-Bipartite Graph 贪心 二分图构建

本文介绍了一种从无向图中构建至少包含m/2条边的平衡二分图的贪心算法,并提供了完整的C++实现代码。通过判断与当前顶点连接的已分配顶点数量来决定其归属,确保最终二分图的平衡。

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

题意:从一个无向图中构建一个二分子图,保证二分图的边至少m/2条边


思路:贪心,对与第i个点,假设前i-1个点已经成为一个二分图,就查看与i相连的点是在二分图左边多还是在二分图右边多,哪边少i点就往哪放


题目链接:http://acm.fzu.edu.cn/problem.php?pid=2141


#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;

const int maxn = 105;
bool g[maxn][maxn];
int n, m;
vector<int> l, r;
int color[maxn];

void cal(int u)
{
    int ans1 = 0, ans2 = 0;
    for(int v = 1; v <= n; v++)
    {
        if(g[u][v] == true)
        {
            if(color[v] == 1)
                ans1++;
            else
                ans2++;
        }

    }
    if(ans1 > ans2)
    {
        color[u] = 2;
        r.push_back(u);
    }
    else
    {
        color[u] = 1;
        l.push_back(u);
    }
}

int main()
{
    int t;
    scanf("%d", &t);
    while(t--)
    {
        l.clear(), r.clear();
        memset(g, false, sizeof(g));
        memset(color, 0, sizeof(color));
        scanf("%d%d", &n, &m);
        for(int i = 0; i < m; i++)
        {
            int u, v;
            scanf("%d%d", &u, &v);
            g[u][v] = g[v][u] = true;
        }
        for(int i = 1; i <= n; i++)
            cal(i);
        int len1  = l.size(), len2 = r.size();
        printf("%d", len1);
        for(int i = 0; i < len1; i++)
            printf(" %d", l[i]);
        printf("\n");
        printf("%d", len2);
        for(int i = 0; i < len2; i++)
            printf(" %d", r[i]);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值