UVA1627TeamThemUp

//UVA1627TeamThemUp
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int MAXN = 100 + 5;
int n, cc;
int G[MAXN][MAXN], color[MAXN], diff[MAXN], d[MAXN][2 * MAXN];
vector<int> team[MAXN][2];
bool dfs(int u, int c) {
	color[u] = c;
	team[cc][c - 1].push_back(u);
	for(int v = 0; v < n; v++) {
		if(u != v && !(G[u][v] && G[v][u])) {//根据建立连通分量 
		    if(color[v] > 0 && color[u] == color[v]) return false;
		    if(!color[v] && !dfs(v, 3 - c)) return false;
	    }
	}
	return true;
}

bool Build_graph() {
	memset(color, 0, sizeof(color));
	cc = 0;
	for(int i = 0; i < n; i++) {
		
		if(!color[i]) {
			team[cc][0].clear();
		    team[cc][1].clear();
			if(!dfs(i, 1)) return false;
			diff[cc] = team[cc][1].size() - team[cc][0].size();
			cc++;
		}
	}
	return true;
}
void print(int ans) {
	vector<int> team1, team2;
	int t;
	for(int i = cc - 1; i >= 0; i--) {
		if(d[i][ans - diff[i] + n]) {
			t = 0; ans -= diff[i];
		}
		else if(d[i][ans + diff[i] + n]) {
			t = 1; ans += diff[i];
		}
		for(int j = 0; j < team[i][t].size(); j++) team1.push_back(team[i][t][j]);
		for(int j = 0; j < team[i][t ^ 1].size(); j++) team2.push_back(team[i][t ^ 1][j]);
	}
	printf("%d", team2.size());
	for(int i = 0; i < team2.size(); i++) printf(" %d", team2[i] + 1);
	printf("\n");
	printf("%d", team1.size());
	for(int i = 0; i < team1.size(); i++) printf(" %d", team1[i] + 1);
	
}
void dp() {
	memset(d, 0, sizeof(d));
    d[0][0 + n] = 1;
    for(int i = 0; i < cc; i++) {
    	for(int j = -n; j <= n; j++) if(d[i][j + n]) {
    		d[i + 1][j + diff[i] + n] = 1;//将i+1个连通分量的1组归到最终的A组中 
    		d[i + 1][j - diff[i] + n] = 1;//将i+1个连通分量的1组归到最终的B组中
		}//两种决策 
	}
	for(int ans = 0; ans <= n; ans++) {
		if(d[cc][ans + n]) {
		    print(ans); return;
		}
		else if(d[cc][-ans + n]) {
			print(-ans); return;
		}
	}
}
int main() {
    int T, kase = 0;
	scanf("%d", &T);
	while(T--) {
		if(kase++) printf("\n");
		scanf("%d", &n);
		int tmp; 
		memset(G, 0, sizeof(G));
		for(int i = 0; i < n; i++) 
		    while(scanf("%d", &tmp) == 1 && tmp) G[i][tmp - 1] = 1;
		if(n == 1 || !Build_graph()) printf("No solution");
		else dp();
		printf("\n");
	}
	return 0;
}
/*
2
5
3 4 5 0
1 3 5 0
2 1 4 5 0
2 3 5 0
1 2 3 4 0
5
2 3 5 0
1 4 5 3 0
1 2 5 0
1 2 3 0
4 3 2 1 0
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值