题解:P6873 [COCI 2013/2014 #6] FONT

· · 题解

我不会告诉你,这道题我做了一个小时

题目描述

要求统计给定 n 个单词中能组成"测试句"(包含全部 26 个小写字母的字符串)的最大数量。

算法描述

本题可以用状压 dp 和搜索,但因为这道题范围很小,就用搜索了主要是不想找虐。

算法思路

用二进制的第 i 为表示是否存在第 i 个字母(如第一位表示 a 等等)。
搜索枚举所有的可能性。

代码思路

预处理:

将单词转化为二进制编码。
计算全部的二进制编码。

核心部分

搜索所有的单词可能性。
通过位或运算合并字母集合。
最后记录答案

时空复杂度

时间复杂度:O(2^n)。
空间复杂度:O(n)。

代码实现

#include<bits/stdc++.h>
#define int long long
#define MAX 0x3f3f3f3f3f3f3f3f
#define MIN -0x3f3f3f3f3f3f3f3f
#define endl "\n"
using namespace std;
const int full = (1<<26)-1;
int ans, n;
vector<int> sum;

void dfs(int pos, int cnt) {
    if(cnt == full) ans++;
    for(int i=pos; i<n; i++)
        dfs(i+1, cnt|sum[i]);
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(nullptr); cout.tie(nullptr);
    cin >> n;
    sum.resize(n);
    for(int i=0; i<n; i++) {
        string s; cin >> s;
        for(char c:s)
            sum[i] |= (1<<(c-'a'));
    }
    dfs(0,0);
    cout << ans;
    return 0;
}

最后,求管理员大神过,qwq。