UVa1627

这道题题意就不说了,说一下思路:

我们发现互相不认识的人一定不会分到同一组,所以我们将互相不认识的人两两之间连一条线段,这样我们就得到了连通图,经过

观察,我们发现将不认识的人分开这样就得到了二分图,后面我们需要通过dp使得最后两组的人数相同,这样我们就得到了该问题的解法。

下面是代码:

// UVa 1627 
// 二分图 + dp
#include <cstdio> 
#include <cstring> 
#include <vector> 
#include <algorithm> 
using namespace std; 

const int maxn = 100 + 10; 

int n, G[maxn][maxn], color[maxn], diff[maxn], cc; 
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[v] == color[u]) 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][0].size() - team[cc][1].size(); 
      cc++;    
    }
  return true; 
}

int d[maxn][maxn*2]; 

void print(int ans) {
  vector<int> team1, team2; 
  for (int i = cc-1; i >= 0; --i) {
    int t; 
    if (d[i][ans-diff[i]+n]) { t = 0; ans -= diff[i]; } 
    else { 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][1^t].size(); ++j)
      team2.push_back(team[i][1^t][j]); 
  }
  printf("%d", team1.size());
  for (int i = 0; i < team1.size(); ++i) printf(" %d", team1[i]+1); 
  printf("\n");
  
  printf("%d", team2.size()); 
  for (int i = 0; i < team2.size(); ++i) printf(" %d", team2[i]+1); 
  printf("\n");
}

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; 
      d[i+1][j-diff[i]+n] = 1;    
    } 
  for (int ans = 0; ans <= n; ++ans) {
    if (d[cc][ans+n]) { print(ans); return; }
    if (d[cc][-ans+n]) { print(-ans); return; }   
  }
}

int main() { 
  int t; 
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n); 
    memset(G, 0, sizeof(G)); 
    for (int u = 0; u < n; ++u) {
      int v; 
      while (scanf("%d", &v) == 1 && v) G[u][v-1] = 1; 
    }
    
    if (n == 1 || !build_graph()) printf("No solution\n"); 
    else dp(); 
    
    if (t) printf("\n"); 
  }
  return 0;
}

 

转载于:https://www.cnblogs.com/yifeiWa/p/11293656.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值