• POJ 1699 Best Sequence dfs


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

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

     1 #include <stdio.h>
     2 #include <string.h>
     3 
     4 char str[10][25];
     5 bool vis[10];
     6 int lenth[10];
     7 int ans, n;
     8 
     9 void dfs(int cnt, int x, char tmp[], int len)
    10 {
    11     if(len > ans)return;
    12     vis[x] = 1;
    13     if(len == 0)
    14     {
    15         strcpy(tmp, str[x]);
    16         len = lenth[x];
    17     }
    18     else
    19     {
    20         int add = (len > lenth[x]) ? len - lenth[x] : 0;
    21         bool ok = 0;
    22         while(add < len)
    23         {
    24             ok = 1;
    25             for(int j = 0; j+add < len; j++)
    26             {
    27                 if(tmp[j+add] != str[x][j])
    28                 {
    29                     ok = 0;
    30                     break;
    31                 }
    32             }
    33             if(ok)
    34             {
    35                 int k = len - add;
    36                 while(k < lenth[x])
    37                     tmp[len++] = str[x][k++];
    38                 break;
    39             }
    40             add++;
    41         }
    42         if(!ok)
    43         {
    44             strcpy(tmp+len, str[x]);
    45             len += lenth[x];
    46         }
    47     }
    48     for(int j = 0; j < n; j++)
    49     {
    50         if(!vis[j])
    51             dfs(cnt-1, j, tmp, len);
    52     }
    53     vis[x] = 0;
    54     if(cnt == 0 && ans > len)
    55     {
    56         ans = len;
    57     }
    58 }
    59 
    60 int main()
    61 {
    62     char tmp[210];
    63     int t;
    64     scanf("%d", &t);
    65     while(t--)
    66     {
    67         memset(vis, 0, sizeof(vis));
    68         ans = 0x3f3f3f3f;
    69         scanf("%d", &n);
    70         for(int i = 0; i < n; i++)
    71         {
    72             scanf("%s", str[i]);
    73             lenth[i] = strlen(str[i]);
    74         }
    75         for(int i = 0; i < n; i++)
    76             dfs(n-1, i, tmp, 0);
    77         printf("%d
    ", ans);
    78     }
    79     return 0;
    80 }
    View Code
  • 相关阅读:
    oracle日志总结
    UIScrollView,contentOffset,contentInsert的各自特点和区别?
    js动态增加表格
    判断某个对象是不是DOM对象
    IOS 中frame与bounds的区别
    删除重复项,只取其中一条数据
    NSBundle
    React
    HTML5 postMessage 和 onmessage API 详解
    SonarQube
  • 原文地址:https://www.cnblogs.com/wolfred7464/p/3442848.html
Copyright © 2020-2023  润新知