Clan Guard Problem Solving Report

Title description:

The inhabitants of the primitive tribe byteland often clashed for limited resources. Almost every resident has his enemy. In order to organize a team to defend the tribe, the tribal chief hopes to select the largest number of residents from the tribe to join the army and ensure that no two people in the team are enemies.

Given the enemy relationship among the residents of the byteland tribe, programming calculates the best plan to form the tribal guard.


Input format:

There are 2 positive integers n and m in the first line, indicating that there are n residents in the byteland tribe, and there are m enemy relations among the residents. Resident numbers are 1, 2,..., n.

In the next m rows, each row has 2 positive integers u and v, indicating that residents u and residents v are enemies.


Output format:

The first line is the total number of the tribal guard; the second line is the composition of the guard xi, 1≤i≤n, xi=0 means that resident i is not in the guard, xi=1 means that resident i is in the guard.


Example:

enter

7 10
1 2
1 4 
2 4 
2 3 
2 5 
2 6 
3 5 
3 6 
4 5 
5 6

Output

3
1 0 1 0 0 0 1

Ideas:

搜索出所有的情况,找出最大的。
能否搜索的条件是,没有加入队伍并且队伍中的人没有他的仇敌。

code:

#include<cstdio>

using namespace std;
const int maxn = 105;
int n, m, mxn;
int a[maxn][maxn],b[maxn],maxx[maxn];
bool check(int k) {
    
    
	for(int i = 1;i <= k;i ++)
		if(b[i] == 1 && a[i][k] == 1)
			return 0;
	return 1;
}
void dfs(int x,int sum) {
    
    
	if(x > n) {
    
    
		if(sum > mxn){
    
    
			mxn = sum;
			for(int i = 1;i <= n;i ++)
				maxx[i] = b[i];
		}
		return ;
	}
	if(check(x)) {
    
    
		b[x] = 1;
		dfs(x+1,sum+1);
		b[x] = 0;
	}
	dfs(x + 1,sum);
}
int main() {
    
    
	scanf("%d %d", &n, &m);
	for(int i = 1;i <= m;i ++) {
    
    
		int x , y;
		scanf("%d %d", &x, &y);
		a[x][y] = 1;
		a[y][x] = 1;
	}
	dfs(1 , 0);
	printf("%d\n", mxn);
	for(int i = 1;i <= n;i ++)
		printf("%d ",maxx[i]);
	return 0;
}

Guess you like

Origin blog.csdn.net/C202207LYX/article/details/108598304