• HDU3460 Ancient Printer 字典树


      该题题意是求给定的字符串集用一个打字机来打出所有的字符串(最后一个),顺序可以打乱,每次操作可以向打字机的末尾添加一个字符删除一个字符以及打印一个单词。这里有一个很强大的想法,那就是先假设每个单词都打印出来起消耗为 sumlenth * 2 + N,在统计所有的相同的字符数 M, 然后得到最长的一个单词的长度L,把这个单词的放在最后打印,最后答案就是 sumlen * 2 + N - M.

      代码如下:

     1 #include <cstdlib>
    2 #include <cstdio>
    3 #include <cstring>
    4 using namespace std;
    5
    6 struct Node
    7 {
    8 int cnt;
    9 Node *child[26];
    10 };
    11
    12 inline Node *init( )
    13 {
    14 Node *p = new Node;
    15 p->cnt = -1;
    16 memset( p->child, 0, sizeof( p->child ) );
    17 return p;
    18 }
    19
    20 inline bool getint( int &t )
    21 {
    22 char c;
    23 int f = 1;
    24 while( c = getchar(), ( c < '0' || c > '9' ) && c != '-' )
    25 if( c == EOF ) return false;
    26 if( c == '-' ) f = -1;
    27 else t = c - '0';
    28 while( c = getchar(), c >= '0' && c <= '9' )
    29 t = t * 10 + c - '0';
    30 return true;
    31 }
    32
    33 inline void getstr( char *s )
    34 {
    35 char c;
    36 int p = 0;
    37 while( c = getchar(), c == ' ' || c == '\n' ) ;
    38 s[p++] = c;
    39 while( c = getchar(), c != ' ' && c != '\n' )
    40 s[p++] = c;
    41 s[p] = '\0';
    42 }
    43
    44 inline void insert( Node *p, char *in )
    45 {
    46 int dx = *in - 'a';
    47 if( *in )
    48 {
    49 if( p->child[dx] == NULL )
    50 p->child[dx] = init();
    51 p->child[dx]->cnt++;
    52 insert( p->child[dx], in + 1 );
    53 }
    54 }
    55
    56 inline void getsum( Node *p, int &cnt )
    57 {
    58 for( int i = 0; i < 26; ++i )
    59 {
    60 if( p->child[i] )
    61 {
    62 cnt += p->child[i]->cnt;
    63 getsum( p->child[i], cnt );
    64 }
    65 }
    66 free( p );
    67 }
    68
    69 int main()
    70 {
    71 int N;
    72 while( getint( N ) )
    73 {
    74 Node *r = init();
    75 char str[55];
    76 int ans = 0, cnt = 0, maxlen = -0x7fffffff;
    77 for( int i = 0; i < N; ++i )
    78 {
    79 getstr( str );
    80 int len = strlen( str );
    81 maxlen = maxlen > len ? maxlen : len;
    82 ans += len;
    83 insert( r, str );
    84 }
    85 getsum( r, cnt );
    86 printf( "%d\n", ( ans - cnt ) * 2 + N - maxlen );
    87 }
    88 }
  • 相关阅读:
    linux 权限管理命令
    大三上学期总结
    C# 读写Excel的一些方法,Aspose.Cells.dll
    Topshelf 创建.net服务整理和安装步骤(转)
    你必须知道的.NET之特性和属性(转)
    用SQL语句删除一个数据库的所有表和所有存储过程
    System.DllNotFoundException: 无法加载 DLL“FileTracker.dll”: 动态链接库(DLL)初始化例
    关于消息队列的使用[转]
    PhpStorm使用技巧小结
    转载]C#实现获取浏览器信息
  • 原文地址:https://www.cnblogs.com/Lyush/p/2168976.html
Copyright © 2020-2023  润新知