Word Construction hiho一下第170周

来源:互联网 发布:a5源码被骗 编辑:程序博客网 时间:2024/05/16 05:36

题意:题目给出100个单词中的 N 个,从中选出尽可能多的单词,且这些单词两两之间不能含有相同的字母。

**思路:**N 最大为40。考虑爆搜,每个单词只有两种情况,要么被选择,要么没被选。且不能含有相同的字母这一点就可以用来剪枝。所以不会超时。

代码:

#include<cstdio>#include<cstring>#include<cstdlib>#include<stack>#include<queue>#include<utility>#include<vector>#include<cmath>#include<set>#include<map>#include<iostream>#include<algorithm>using namespace std;typedef long long LL;int N;char word[45][10];bool alph[30];int ans;void Dfs(int pos, int wordnum){    if(pos == N){        ans = max(ans, wordnum);        return ;    }    Dfs(pos+1, wordnum);  //没被选    bool ok = true;    int len = strlen(word[pos]);    for(int i=0; i<len; i++){        if(alph[word[pos][i]-'a']){            ok = false;            break;   //判断和之前的单词是否含有相同的字母,如果有则不能选,如果没有则可以选        }    }    if(ok){        for(int i=0; i<len; i++){            alph[word[pos][i]-'a'] = true;        }        Dfs(pos+1, wordnum+1);        for(int i=0; i<len; i++){  //恢复原状,以免影响其他的Dfs            alph[word[pos][i]-'a'] = false;        }    }}int main(){    //freopen("in.txt", "r", stdin);    while(scanf("%d", &N) == 1){        for(int i=0; i<N; i++){            scanf("%s", word[i]);        }        memset(alph, false, sizeof(alph));        ans = 0;        Dfs(0, 0);        printf("%d\n", ans);    }    return 0;}
原创粉丝点击