hdu3746 KMP的next数组应用,求项链首尾项链循环
生活随笔
收集整理的這篇文章主要介紹了
hdu3746 KMP的next数组应用,求项链首尾项链循环
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題意:
? ? ? 給你一個項鏈,問你最少加多少個珠子能滿足整個項鏈是一個循環的項鏈(首尾相連)
思路:
? ? ?KMP的簡單應用只要了解next數組的意義就好說了,下面總結下
?next在循環方面的常用應用
(1)i - next[i] 最小循環節(第一個字母開始)
(2)next[i] 最大循環節中的第幾位數(此時循環節可交叉)
(3)next[i] != 0 && i % (i - next[i]) == 0,當前是循環節中的最 ??后一位.
(4)在(3)的前提下 i / (i - next[i]) 表示的最大周期個數,也就是在最小循環節的前提下的最大周期個數。那么這個題目就好辦了,先求出,如果next[n] && n % (n - next[n])
? ? ? 給你一個項鏈,問你最少加多少個珠子能滿足整個項鏈是一個循環的項鏈(首尾相連)
思路:
? ? ?KMP的簡單應用只要了解next數組的意義就好說了,下面總結下
?next在循環方面的常用應用
(1)i - next[i] 最小循環節(第一個字母開始)
(2)next[i] 最大循環節中的第幾位數(此時循環節可交叉)
(3)next[i] != 0 && i % (i - next[i]) == 0,當前是循環節中的最 ??后一位.
(4)在(3)的前提下 i / (i - next[i]) 表示的最大周期個數,也就是在最小循環節的前提下的最大周期個數。那么這個題目就好辦了,先求出,如果next[n] && n % (n - next[n])
直接輸出0,因為此時最后一個是循環節上的數字,并且是最后一個。否則就輸出(n - next[n]) - n % (n - next[n])
#include<stdio.h> #include<string.h>#define N 100000 + 100 int next[N]; char str[N];void get_next(int m) {int j ,k;j = 0 ,k = -1;next[0] = -1;while(j < m){if(k == -1 || str[j] == str[k])next[++j] = ++k;elsek = next[k];}return ; }int main () {int t ,i ,m;scanf("%d" ,&t);while(t--){scanf("%s" ,str);m = strlen(str);get_next(m);if(next[m] && m % (m - next[m]) == 0)puts("0");elseprintf("%d\n" ,(m - next[m]) - m % (m - next[m]));}return 0; }
總結
以上是生活随笔為你收集整理的hdu3746 KMP的next数组应用,求项链首尾项链循环的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hdu4067 费用流(混合欧拉的宽展和
- 下一篇: hdu1358 最小循环节,最大循环次数