UVA - 11218 KTV(暴力求解)

Problem K

KTV

One song is extremely popular recently, so you and your friends decided to sing it in KTV. The song has 3 characters, so exactly 3 people should sing together each time (yes, there are 3 microphones in the room). There are exactly 9 people, so you decided that each person sings exactly once. In other words, all the people are divided into 3 disjoint groups, so that every person is in exactly one group.

However, some people don't want to sing with some other people, and some combinations perform worse than others combinations. Given a score for every possible combination of 3 people, what is the largest possible score for all the 3 groups?

Input

The input consists of at most 1000 test cases. Each case begins with a line containing a single integer  n  (0 <  n  < 81), the number of possible combinations. The next  n  lines each contains 4 positive integers  a b c s  (1 <=  a  <  b  <  c  <= 9, 0 <  s  < 10000), that means a score of  s  is given to the combination (  a b c ). The last case is followed by a single zero, which should not be processed.

Output

For each test case, print the case number and the largest score. If it is impossible, print -1.

Sample Input

3
1 2 3 1
4 5 6 2
7 8 9 3
4
1 2 3 1
1 4 5 2
1 6 7 3
1 8 9 4
0

Output for the Sample Input

Case 1: 6
Case 2: -1

题目大意:
  有9个人去KTV唱歌,每组3人分在一组唱歌,一人只能分在一个组里。然而不同的组合效果不同,而且某些人不想跟某些人同一组。所以不同的组合的得分是不同的。
现在给你n个组合,每组3人分别是a,b,c,和其相应的分数s,找出其中三个组合,使得1~9恰好各出现一次,且分数最大, 求出这些组合中最高能得到的总分是多少。

解析:只需要暴力的回溯枚举出符合条件的情况,取其中最高的分数及可。


#include <cstdio>
#include <cstring>
using namespace std;
struct Node{
	int a,b,c,s;
}com[90];
int vis[10];
int n;
int max;
void dfs(int cur,int group,int sum) {
	if(group == 3) {
		if(sum > max) {
			max = sum;
		}
		return ;
	}
	if(cur == n) {
		return ;
	}
	if(!vis[com[cur].a] && !vis[com[cur].b] && !vis[com[cur].c]) { //如果满足条件回溯
		vis[com[cur].a] = true;
		vis[com[cur].b] = true;
		vis[com[cur].c] = true;
		dfs(cur+1,group+1,sum + com[cur].s);
		vis[com[cur].a] = false;
		vis[com[cur].b] = false;
		vis[com[cur].c] = false;
	}
	dfs(cur+1,group,sum); //如果不满足条件,查找下一个组合
}
int main() {
	int cas = 1;
	while(scanf("%d",&n) != EOF && n) {
		for(int i = 0; i < n; i++) {
			scanf("%d%d%d%d",&com[i].a,&com[i].b,&com[i].c,&com[i].s);
		}
		memset(vis,0,sizeof(vis));
		max = -1;
		dfs(0,0,0);
		printf("Case %d: %d\n",cas++,max);
	}
	return 0;
}


你可能感兴趣的:(uva,ktv,11218)