码迷,mamicode.com
首页 > 其他好文 > 详细

uva 11218 KTV(DFS+回溯)

时间:2015-02-05 18:35:13      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:c语言   uva   

                                 uva 11218 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


题目大意:第一行的数据代表接下来的组数N,接下来的N行前三个数据代表编号,最后一个数据是分数。要求从中选3行,使得9个编号都出现,并且分数和最大。

解题思路:DFS + 回溯。


#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
using namespace std;
int Max, n, vis[10];
struct T {
	int a, b, c, d;
};
T t[100];
int DFS(int d, int sum) {
	if (d >= 3) {
		if (Max < sum) {
			Max = sum;
			return 1;
		}
	}
	for (int i = 0; i < n; i++) {
		if (!vis[t[i].a] && !vis[t[i].b] && !vis[t[i].c]) {
			vis[t[i].a] = vis[t[i].b] = vis[t[i].c] = 1;
			DFS(d + 1, sum + t[i].d);
			vis[t[i].a] = vis[t[i].b] = vis[t[i].c] = 0; //回溯
		}
	}
}
int main() {
	int Case = 1;;
	while (scanf("%d", &n) == 1, n) {
		memset(vis, 0, sizeof(vis));
		Max = -1;
		for (int i = 0; i < n; i++) {
			scanf("%d %d %d %d", &t[i].a, &t[i].b, &t[i].c, &t[i].d);
		}
		DFS(0, 0);
		printf("Case %d: %d\n", Case++, Max);
	}
return 0;
}





uva 11218 KTV(DFS+回溯)

标签:c语言   uva   

原文地址:http://blog.csdn.net/llx523113241/article/details/43529465

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!