POJ 1699 Best Sequence dfs

时间:2023-03-09 02:45:14
POJ 1699 Best Sequence  dfs

题目: http://poj.org/problem?id=1699

无意间A了。。超时一次,加了一句 if(len > ans)return; 然后就A了,dfs题,没有太多好说的,代码写的效率高一点就行。

 #include <stdio.h>
#include <string.h> char str[][];
bool vis[];
int lenth[];
int ans, n; void dfs(int cnt, int x, char tmp[], int len)
{
if(len > ans)return;
vis[x] = ;
if(len == )
{
strcpy(tmp, str[x]);
len = lenth[x];
}
else
{
int add = (len > lenth[x]) ? len - lenth[x] : ;
bool ok = ;
while(add < len)
{
ok = ;
for(int j = ; j+add < len; j++)
{
if(tmp[j+add] != str[x][j])
{
ok = ;
break;
}
}
if(ok)
{
int k = len - add;
while(k < lenth[x])
tmp[len++] = str[x][k++];
break;
}
add++;
}
if(!ok)
{
strcpy(tmp+len, str[x]);
len += lenth[x];
}
}
for(int j = ; j < n; j++)
{
if(!vis[j])
dfs(cnt-, j, tmp, len);
}
vis[x] = ;
if(cnt == && ans > len)
{
ans = len;
}
} int main()
{
char tmp[];
int t;
scanf("%d", &t);
while(t--)
{
memset(vis, , sizeof(vis));
ans = 0x3f3f3f3f;
scanf("%d", &n);
for(int i = ; i < n; i++)
{
scanf("%s", str[i]);
lenth[i] = strlen(str[i]);
}
for(int i = ; i < n; i++)
dfs(n-, i, tmp, );
printf("%d\n", ans);
}
return ;
}