hihocoder 1334 - Word Construction - [hiho一下第170周][状态压缩+DFS]

时间:2023-12-18 23:46:32

题目链接:https://hihocoder.com/problemset/problem/1334

时间限制:10000ms
单点时限:1000ms
内存限制:256MB

描述

Given N words from the top 100 common words in English (see below for reference), select as many words as possible as long as no two words share common letters.

Assume that the top 100 common words in English are:

the be to of and a in that have i it for not on with he as you do at this but his by from they we say her she or an will my one all would there their what so up out if about who get which go me when make can like time no just him know take people into year your good some could them see other than then now look only come its over think also back after use two how our work first well even new want because any these give day most us

输入

The first line contains an integer N, denoting the number of words. (1 ≤ N ≤ 40)

The second line contains N words from the top 100 common words.

输出

Output the most number of words can be selected.

样例输入
8
the be to of and a in that
样例输出
4

题意:

给出N个单词(1 ≤ N ≤ 40),在满足各个单词之间没有重复字母的情况下,求能选取最多多少个单词。

题解:

每个单词总共24个字母,用状态压缩之后,可以表示为小于2^24的整数;

而且能很方便的表示当前哪些字母被占用了,哪些字母还没占用,选某个单词又会占用哪些字母;

并且用过位运算能很方便地进行判断是否有重复字母;

最后,直接DFS即可;

AC代码:

 #include<cstdio>
#include<cstring>
#include<algorithm>
#define MAX 43
using namespace std;
int n,word[MAX];
bool vis[MAX];
int dfs(int now,int state)
{
int maxi=;
for(int nex=;nex<=n;nex++)
{
if(vis[nex]) continue;
if(state&word[nex]) continue;
vis[nex]=;
maxi=max(maxi,dfs(nex,state|word[nex]));
vis[nex]=;
}
return now==?maxi:maxi+;
}
int main()
{
scanf("%d",&n);
for(int i=;i<=n;i++)
{
char str[];
scanf("%s",&str);
word[i]=;
for(int j=;str[j];j++) word[i]|=<<(str[j]-'a');
}
memset(vis,,sizeof(vis));
int ans=dfs(,);
printf("%d\n",ans);
}