fzu 2141 Sub-Bipartite Graph 贪心 二分图构建
2016-07-22 09:14
344 查看
题意:从一个无向图中构建一个二分子图,保证二分图的边至少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;
}
思路:贪心,对与第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;
}
相关文章推荐
- 1.一些 贪心算法 的简单思维题:
- 贪心算法——字典序最小问题
- 贪心算法——区间调度问题
- Jump Game I,II 贪心
- Wildcard Matching
- 贪心法实现无向图的划分 代码
- 贪心题目循环和控制台折行
- HDOJ 1009
- 【解题报告】【USACO】酸奶工厂
- 【解题报告】【】交谊舞
- POJ 1328
- Best Cow Line
- HDU 1009 Fatmouse's Trade
- POJ2377 Bad Cowtractors
- 贪心 hdu 1003
- 最大容器
- 满足和为定值的两个数或多个数
- Codeforces Round #300
- HUD1052 __ P2 1002 __ Tian Ji -- The Horse Racing
- 2015年国家集训队测试 BZOJ3816矩阵变幻