1611: Concatenation
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 50 Solved: 13
[ Submit][ Status][ Web Board]
Description
Zuosige always has bad luck. Recently, he is in hospital because of pneumonia. While he is taking his injection, he feels extremely bored. However, clever Zuosige comes up with a new game.
Zuosige writes some of his favorite strings on paper. And he wants to find out a string which has all these favorite strings as its substrings. However, as a sick man, he cannot remember a very long string, so he wants you to help him find out the shortest one.
Input
The first line contains one integer T, indicating the number of test cases.
In one test case, there are several lines.
In the first line, there are two integers n (1<=n<=12), indicating the number of strings he writes.
In the following n lines, each line has a string whose length is no more than 50. The strings only consists of uppercase letters.
Output
For each test case, output an integer indicating the length of the shortest string containing all these strings.
Sample Input
1
2
ABCD
BCDABC
Sample Output
7
状态压缩题目。
#include<iostream>
#include<cstdio>
#include<cstring>
#define INF 0x3f3f3f3f
using namespace std;
int dp[1<<12][55],hsh[13][55],len[13];
char c[13][55],c1[13][55];
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
for(int i=0; i<n; i++)
scanf("%s",c[i]);
int cos=0;
for(int i=0; i<n; i++)
{
bool flag=1;
for(int j=0; j<n; j++)
if(strcmp(c[i],c[j])&&strstr(c[j],c[i])) flag=0; //找到是否存在包含i的字串且与i不相同
if(flag) strcpy(c1[cos++],c[i]);
}
n=0;
for(int i=0;i<cos;i++)
{
bool flag=1;
for(int j=0;j<i;j++)
if(strcmp(c1[i],c1[j])==0) flag=0; //剔除相同的字符串
if(flag) strcpy(c[n],c1[i]),len[n]=strlen(c[n]),n++;
}
memset(hsh,0,sizeof(hsh));
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
hsh[i][j]=len[j];
int ans=-1;
for(int k=len[i]-1;k>0;k--)
{
bool flag=0;
for(int l=k;l<len[i];l++)
{
if(c[i][l]!=c[j][l-k]) flag=1;
}
if(!flag) ans=k;
}
if(ans!=-1) hsh[i][j]=len[j]-len[i]+ans; //j接到i后增加的长度
}
}
memset(dp,INF,sizeof(dp));
int Max=(1<<n);
for(int i=1;i<Max;i++)
{
for(int j=0;j<n;j++)
{
if((1<<j)&i)
{
if((i^(1<<j))==0) dp[i][j]=len[j];
for(int k=0;k<n;k++)
{
int next=(1<<k)|i;
if((j!=k&&(1<<k)&i)==0)
dp[next][k]=min(dp[next][k],dp[i][j]+hsh[j][k]);
}
}
}
}
int Min=INF;
for(int i=0;i<n;i++)
Min=min(Min,dp[Max-1][i]);
printf("%d\n",Min);
}
}