您的位置:首页 > 其它

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

2015-07-20 16:11 489 查看
题意:

问题描述
青年理论计算机科学家wyh2000在教导他的小学生。
共有n个小学生,编号为1−n。为了增加小学生之间的凝聚力,wyh2000决定将所有小学生分成2组,每组都至少有1个人。
但是有些小学生之间并不认识,而且如果a不认识b,那么b也不认识a。
Wyh2000希望每组中的小学生都互相认识。而且第一组的人要尽可能多。
请你帮wyh2000求出第一组和第二组的人数是多少。如果找不到分组方案,则输出"Poor wyh"。

输入描述
第一行一个数T,表示数据组数。
对于每组数据,第一行两个数n,m,表示小学生数量和互相不认识的小学生的数量。
接下来m行,每行两个数x,y(x<y),表示x不认识y,y不认识x。保证一对(x,y)只会出现一次。
T≤10,0≤n,m≤100000

输出描述
对于每组数据,输出答案。

输入样例
2
8 5
3 4
5 6
1 2
5 8
3 5
5 4
2 3
4 5
3 4
2 4

输出样例
5 3
Poor 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 | 1

using 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: