LA2965 Jurassic Remains --- DFS

题意:给定n个只含大写字母的字符串(1<=n<=24),选尽量多的字符串,使得每个大写字母出现次数为偶数

题解:因为n很小,所以直接dfs,对每个字符串选择和不选择进行搜索没问题。

因为出现偶数次,所以单个字符每出现2次就等于没出现,所以可以用0表示未出现,1表示出现,这样26个英文字母可以用位运算的方式表示出来。然后dfs到尽头的时候,判断选择的所有字符串异或结果是否是零即可。 

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    int n;
    char s[1000];
    int bit[1000];
    int res;
    int order[1000];
    int temp[1000];

    void DFS(int depth, int bits,int cnt) {
        if(depth == n) {
            if(bits == 0 && cnt > res) {
                res = cnt;
                memcpy(order,temp,sizeof(temp));
            }
            return;
        }
        // choose bit[i] or not
        temp[cnt] = depth+1;
        DFS(depth+1,bits^bit[depth],cnt+1);
        temp[cnt] = 0;
        DFS(depth+1,bits,cnt);
    }

    int main() {
        while(scanf("%d",&n) == 1 && n) {
            memset(bit,0,sizeof(bit));
            res = 0;
            memset(order,0,sizeof(order));
            memset(temp,0,sizeof(temp));
            for(int i = 0;i < n;i++) {
                scanf("%s",s);
                int cur = 0;
                while(s[cur] != '\0') {
                    bit[i] ^= 1<<(s[cur]-'A');
                    cur++;
                }
            }
            res = 0;
            DFS(0,0,0);
            printf("%d\n",res);
            for(int i = 0;i < res;i++) {
                printf("%d%s",order[i],i==(res-1)?"\n":" ");
            }
            printf("\n");
        }

        return 0;
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值