(简单) 状态压缩dp HOJ 2188 WordStack

WordStack

Source : Mid-Atlantic 2005
Time limit : 5 secMemory limit : 32 M

Submitted : 219, Accepted : 116

As editor of a small-town newspaper, you know that a substantial number of your readers enjoy the daily word games that you publish, but that some are getting tired of the conventional crossword puzzles and word jumbles that you have been buying for years. You decide to try your hand at devising a new puzzle of your own.

Given a collection of N words, find an arrangement of the words that divides them among N lines, padding them with leading spaces to maximize the number of non-space characters that are the same as the character immediately above them on the preceding line. Your score for this game is that number.

Input

Input data will consist of one or more test sets.

The first line of each set will be an integer N (1 <= N <= 10) giving the number of words in the test case. The following N lines will contain the words, one word per line. Each word will be made up of the characters ’a’ to ’z’ and will be between 1 and 10 characters long (inclusive).

End of input will be indicated by a non-positive value for N.

Output

Your program should output a single line containing the maximum possible score for this test case, printed with no leading or trailing spaces.

Sample Input

5
abc
bcd
cde
aaa
bfcde
0
Sample Output
8

One possible arrangement yielding this score is:

aaa
abc
 bcd
  cde
bfcde

题意:给出N个单词,要你重新排列它们,可以在它们前面加上空格,当一行的单词的有x个字母与上一行的单词相对应的位置的字母一样,那么你能获得x分,问最最多能获得多少分

思路:因为N最大只有10,然后又要考虑选择的先后顺序,所以我们想到用状态压缩,我们用dp[state][i] 表示状态为state,目前最后一行为i单词的最大分数, 于是状态转移方程就是 dp[state][i] = max(dp[state][i],dp[state-x][j]+w[j][i])

代码:

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;

const int maxn = 1<<11;

int dp[maxn][11];
int inc[11][11];

char word[20][20];
int n;

void getsame()
{
for (int i = 0 ; i < n ; ++i)
{
for (int j = i+1 ; j < n ; ++j)
{
int len1 = strlen(word[i]);
int len2 = strlen(word[j]);
for (int ii = 0 ; ii < len1 ; ++ii)
for (int jj = 0 ; jj < len2 ; ++jj)
{
int cnt = 0;
for (int k = 0 ; ii+k<len1 && jj+k<len2 ; ++k)
{
if (word[i][ii+k]==word[j][jj+k])
++cnt;
}
inc[i][j] = max(inc[i][j],cnt);
}
inc[j][i] = inc[i][j];
}
}
}

int main()
{
while (scanf("%d",&n) , n)
{
for (int i = 0 ; i < n ; ++i)
scanf("%s",word[i]);
memset(inc,0,sizeof(inc));
getsame();
int max_state = 1<<n;
memset(dp,0,sizeof(dp));
for (int s = 0 ; s < max_state ; ++s)
{
for (int j = 0 ; j < n ; ++j) if (s&(1<<j))
{
for (int k = 0 ; k < n ; ++k) if (s^(1<<k))
{
int to = s+(1<<k);
if (dp[to][k] < dp[s][j]+inc[j][k])
dp[to][k] = dp[s][j]+inc[j][k];
}
}
}
int ans = 0;
for (int i = 0 ; i < n ; ++i)
if (dp[max_state-1][i] > ans)
ans = dp[max_state-1][i];
printf("%d\n",ans);
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值