Word Construction hiho一下第170周

针对一个特定的问题,即从给定的单词集合中选择尽可能多的单词,且这些单词之间不能有相同的字母,本文详细介绍了如何通过深度优先搜索算法进行求解的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:题目给出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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值