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?
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
Case 1: 6 Case 2: -1题目大意:有9个人,给出一些3人的组合,要求9人的组合值最高。
解题思路:DFS+回溯。
#include<stdio.h> #include<string.h> #define N 1005 struct coor{ int x; int y; int z; int value; }que[N]; int n, cnt, max, vis[10]; void DFS(int k, int sum){ vis[que[k].x] = vis[que[k].y] = vis[que[k].z] = 1; cnt += 3; sum += que[k].value; if (cnt == 9){ if (max < sum) max = sum; } else{ for (int i = k + 1; i < n; i++){ if (vis[que[i].x] || vis[que[i].y] || vis[que[i].z]) continue; DFS(i, sum); } } vis[que[k].x] = vis[que[k].y] = vis[que[k].z] = 0; cnt -= 3; } int main(){ int t = 1; while (scanf("%d", &n), n){ // Init. memset(vis, 0, sizeof(vis)); memset(que, 0, sizeof(vis)); max = cnt = 0; // Read. for (int i = 0; i < n; i++) scanf("%d%d%d%d", &que[i].x, &que[i].y, &que[i].z, &que[i].value); for (int i = 0; i < n; i++) DFS(i, 0); if (max) printf("Case %d: %d\n", t++, max); else printf("Case %d: -1\n", t++); } return 0;}