UVA --11218 KTV(DFS+回溯)

##Problem
## 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

Sample Output
Case 1: 6
Case 2: -1


题目大意:
有9个人去KTV唱歌,三个人一组,分为三组,且一个人只能进一组。有些人不想和其他某些人一起唱歌,所以不同的分组最后的歌曲得分是不一样的。
现在有n组,每组有3人编号依次为a,b,c,相对应歌曲得分为s。现在找出其中三组,使得每个人都只出现一次,且总分得分最高。找出并求得最高得分的三组。

解题方法:
用DFS暴力枚举出所有情况,找出最高得分。


代码如下:

#include<iostream>
#include<string.h>
using namespace std;

int n;
bool vis[15];
int maxn;

struct
{
    int a,b,c,s;
} comb[85];

void dfs(int t,int sum)
{

    for(int i=0; i<n; i++)
    {
        if(t==3)
        {
            if(maxn<sum)
                maxn=sum;
            return;
        }
        if(!vis[comb[i].a]&&!vis[comb[i].b]&&!vis[comb[i].c])
        {
            vis[comb[i].a]=vis[comb[i].b]=vis[comb[i].c]=1;
            // sum+=comb[i].s;          此处是我之前的错误,改变了sum的值,导致在回溯过程中出错
            dfs(t+1,sum+comb[i].s);
            vis[comb[i].a]=vis[comb[i].b]=vis[comb[i].c]=0;
        }
    }
}

int main()
{
    int i;
    int p=1;
    while(cin>>n)
    {
        if(!n) break;
        maxn=-1;
        memset(vis,0,sizeof(vis));
        for(i=0; i<n; i++)
        {
            cin>>comb[i].a>>comb[i].b>>comb[i].c>>comb[i].s;
        }
        dfs(0,0);
        cout<<"Case "<<p++<<": "<<maxn<<endl;
    }
}


现在来分析一下前面那个我师兄说很智障,但是我觉得很有意义的错误(其实就是我很菜)。

错误代码:

sum+=comb[i].s;          
dfs(t+1,sum);

在回溯过程中这个问题就暴露出来了,导致结果成了这样:
(其中的过程很有意思,可以自己改变输入输出看看其中的过程)

3
1 2 3 1
4 5 6 2
7 8 9 3
Case 1: 10
4
1 2 3 1
1 4 5 2
1 6 7 3
1 8 9 4
Case 2: -1
0

~不积跬步无以至千里,不积小流无以成江海

发布了37 篇原创文章 · 获赞 23 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/zsheng_/article/details/76165936