明天开始电工实习了,不用上课了
题意:
给一个简单图,n点m边,求一个子图,为二分图,同时这个子图包含至少m/2条边,保证测试数据包含至少一种合法子图。
Input
The first line of the date is an integer T, which is the number of the text cases.
Then T cases follow, each case starts of two numbers N and M, representing the number of vertices and the number of edges, then M lines follow. Each line contains two integers x and y, means that there is an edge connected x and y. The number of nodes is from 1 to N.
1 <= T <= 100, 1 <= N <= 100, 0 <= M <= 10086
Output
For each case, you should output two lines to describe your sub-graph, the first line is the set of U and the second line is the set of V.
Each line should output an integer F first, which is the total number of the vertices in this set, then F integers follow which are the number of each vertex of this part, see sample input and sample output for more details.
You can assume that the answer is always existed.
看到是图论就先吓尿了,看到是二分图就更吓尿了,比赛完了才知道其实是相当简单的贪心。对于每一个点来说,统计它的所有边,计算相连所有已涂色点的涂色,选取数量比较少的那种涂色,如数目相等则随意,这样贪心虽然不是最优的,但是这样会保证每次选择都会增加大于等于考虑范围内边数量(与未染色的点相连的边不算考虑范围内)的二分之一,所有总数必然大于等于m/2。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define mxn 110
#define mxm 11000
int n,m;
int first[mxn],nxt[mxm],vv[mxm],cnt;
void add(int u,int v){
nxt[cnt]=first[u];
first[u]=cnt;
vv[cnt++]=v;
}
void init(){
memset(first,-1,sizeof(first));
cnt=0;
}
int color[mxn];
int bcnt,wcnt;
void solve(){
memset(color,0,sizeof(color));
bcnt=0, wcnt=0;
for(int i=1;i<=n;++i){
int tb=0,tw=0;
for(int j=first[i];j!=-1;j=nxt[j])
if(color[vv[j]]==1) ++tb;
else if(color[vv[j]]==2) ++tw;
if(tb>tw){
color[i]=2;
++wcnt;
}
else{
color[i]=1;
++bcnt;
}
}
}
int main(){
int cs,CS=0;
scanf("%d",&cs);
while(cs--){
init();
scanf("%d%d",&n,&m);
for(int i=0;i<m;++i){
int u,v;
scanf("%d%d",&u,&v);
add(u,v);
add(v,u);
}
solve();
printf("%d",bcnt);
for(int i=1;i<=n;++i) if(color[i]==1)
printf(" %d",i);
printf("\n%d",wcnt);
for(int i=1;i<=n;++i) if(color[i]==2)
printf(" %d",i);
puts("");
}
return 0;
}