hdu 5285 dfs染色+贪心(bc #48 B)

来源:互联网 发布:北山狼淘宝 编辑:程序博客网 时间:2024/04/29 18:10

题意:

问题描述
青年理论计算机科学家wyh2000在教导他的小学生。共有n个小学生,编号为1n。为了增加小学生之间的凝聚力,wyh2000决定将所有小学生分成2组,每组都至少有1个人。但是有些小学生之间并不认识,而且如果a不认识b,那么b也不认识a。Wyh2000希望每组中的小学生都互相认识。而且第一组的人要尽可能多。请你帮wyh2000求出第一组和第二组的人数是多少。如果找不到分组方案,则输出"Poor wyh"。
输入描述
第一行一个数T,表示数据组数。对于每组数据,第一行两个数n,m,表示小学生数量和互相不认识的小学生的数量。接下来m行,每行两个数x,y(x<y),表示x不认识yy不认识x。保证一对(x,y)只会出现一次。T10,0n,m100000
输出描述
对于每组数据,输出答案。
输入样例
28 53 45 61 25 83 55 42 34 53 42 4
输出样例
5 3Poor wyh


解析:

dfs染色,加一个贪心。

cntA, cntB 用来计算当前组内人的个数,然后要取大的。

最后直接判断,如果相邻点染的是同一种颜色,就false。


代码:

#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vector>#include <queue>#include <map>#include <climits>#include <cassert>#define LL long long#define lson lo, mi, rt << 1#define rson mi + 1, hi, rt << 1 | 1using namespace std;const int maxn = 100000 + 10;const int inf = 0x3f3f3f3f;const double eps = 1e-8;const double pi = acos(-1.0);const double ee = exp(1.0);int cntA;int cntB;int col[maxn];int n, m;vector<int> g[maxn];void init(){    memset(col, -1, sizeof(col));    for (int i = 1; i <= n; i++)    {        g[i].clear();    }}void dfs(int u, int color){    col[u] = color;    if (color)        cntA++;    else        cntB++;    for (int i = 0; i < g[u].size(); i++)    {        int v = g[u][i];        if (col[v] == -1)        {            dfs(v, !color);        }    }}int main(){#ifdef LOCAL    freopen("in.txt", "r", stdin);#endif // LOCAL    int ncase;    scanf("%d", &ncase);    while (ncase--)    {        scanf("%d%d", &n, &m);        init();        for (int i = 0; i < m; i++)        {            int u, v;            scanf("%d%d", &u, &v);            g[u].push_back(v);            g[v].push_back(u);        }        if (n <= 1)        {            printf("Poor wyh\n");            continue;        }        if (m == 0)        {            printf("%d 1\n", n - 1);            continue;        }        int ans = 0;        bool flag = true;        for (int i = 1; i <= n; i++)        {            if (col[i] == -1)            {                cntA = 0;                cntB = 0;                dfs(i, 0);                ans += max(cntA, cntB);            }        }        for (int i = 1; i <= n; i++)        {            for (int j = 0; j < g[i].size(); j++)            {                if (col[i] == col[g[i][j]])                {                    flag = false;                    break;                }            }            if (!flag)                break;        }        if (flag)        {            printf("%d %d\n", ans, n - ans);        }        else        {            printf("Poor wyh\n");        }    }    return 0;}


0 0
原创粉丝点击