zoukankan      html  css  js  c++  java
  • hdu 3374 String Problem (字符串最小最大表示 + KMP求循环节)

     
    KMP求循环节。
     
      循环节推导的证明相当的好,这题是很裸的套算法的题。
    代码如下:
     1 #include <cstdio>
     2 #include <cstring>
     3 #include <iostream>
     4 #include <algorithm>
     5 
     6 using namespace std;
     7 
     8 const int N = 1111111;
     9 char buf[N];
    10 int next[N];
    11 
    12 void getNext(char *str) {
    13     char *si = str;
    14     int *ni = next;
    15     int j = *next = -1;
    16     while (*si) {
    17         while (j > -1 && *si != *(str + j)) j = *(next + j);
    18         si++, ni++, j++;
    19 //        if (*si == *(str + j)) *ni = *(next + j);
    20 //        else *ni = j;
    21         *ni = j;
    22     }
    23 }
    24 
    25 int minMaxExp(char *s, bool mini) {
    26     int i = 0, j = 1, k = 0, t;
    27     int len = strlen(s);
    28     while (i < len && j < len && k < len) {
    29 //        cout << i << ' ' << j << ' ' << k << endl;
    30         t = s[(i + k) % len] - s[(j + k) % len];
    31         if (!t) k++;
    32         else {
    33             if (mini ^ (t > 0)) j += k + 1;
    34             else i += k + 1;
    35             if (i == j) j++;
    36             k = 0;
    37         }
    38     }
    39     return min(i, j);
    40 }
    41 
    42 int main() {
    43     while (cin >> buf) {
    44         getNext(buf);
    45 //        for (int i = 0, sz = strlen(buf); i < sz; i++) cout << next[i] + 1 << ' '; cout << endl;
    46         int cycle = strlen(buf);
    47 //        cout << "got next" << endl;
    48         cycle /= (cycle - next[cycle - 1] - 1);
    49         cout << minMaxExp(buf, true) + 1 << ' ' << cycle << ' ' << minMaxExp(buf, false) + 1 << ' ' << cycle << endl;
    50     }
    51     return 0;
    52 }
    View Code
     
    ——written by Lyon
  • 相关阅读:
    分分钟搞定Python之排序与列表
    分分钟搞定Python之排序与列表
    联系我
    联系我
    联系我
    联系表单 1_copy
    联系表单 1_copy
    联系表单 1_copy
    联系表单 1
    联系表单 1
  • 原文地址:https://www.cnblogs.com/LyonLys/p/hdu_3374_Lyon.html
Copyright © 2011-2022 走看看