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

题意:从一个无向图中构建一个二分子图,保证二分图的边至少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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章