码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-10-07 14:54:55      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:man   mem   cstring   time   hihocoder   string   0ms   think   div   

题目链接: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代码:

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 #define MAX 43
 5 using namespace std;
 6 int n,word[MAX];
 7 bool vis[MAX];
 8 int dfs(int now,int state)
 9 {
10     int maxi=0;
11     for(int nex=1;nex<=n;nex++)
12     {
13         if(vis[nex]) continue;
14         if(state&word[nex]) continue;
15         vis[nex]=1;
16         maxi=max(maxi,dfs(nex,state|word[nex]));
17         vis[nex]=0;
18     }
19     return now==0?maxi:maxi+1;
20 }
21 int main()
22 {
23     scanf("%d",&n);
24     for(int i=1;i<=n;i++)
25     {
26         char str[10];
27         scanf("%s",&str);
28         word[i]=0;
29         for(int j=0;str[j];j++) word[i]|=1<<(str[j]-a);
30     }
31     memset(vis,0,sizeof(vis));
32     int ans=dfs(0,0);
33     printf("%d\n",ans);
34 }

 

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

标签:man   mem   cstring   time   hihocoder   string   0ms   think   div   

原文地址:http://www.cnblogs.com/dilthey/p/7634237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!