B - Power Strings POJ - 2406(暴力枚举+Hash)

分析

  • 题意
  1. 判断某个字符串的循环节是几位
  • 思路
  1. 预处理字符串的hash值,从大到小暴力枚举 循环节位数,通过通过 for循环判断每一个定长度的hash值是否相同

代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
/* #include  */
#include 
void fre() { system("clear"), freopen("A.txt", "r", stdin); freopen("Ans.txt","w",stdout); }
void Fre() { system("clear"), freopen("A.txt", "r", stdin);}
#define ios ios::sync_with_stdio(false)
#define Pi acos(-1)
#define pb push_back
#define fi first
#define se second
#define ll long long
#define ull unsigned long long
#define db double
#define Pir pair
#define m_p make_pair
#define INF 0x3f3f3f3f
#define esp 1e-7
#define mod (ll)(1e9 + 7)
#define for_(i, s, e) for(int i = (ll)(s); i <= (ll)(e); i ++)
#define rep_(i, e, s) for(int i = (ll)(e); i >= (ll)(s); i --)
#define sc scanf
#define pr printf
#define sd(a) scanf("%d", &a)
#define ss(a) scanf("%s", a)
using namespace std;

const int mxn = 1e6 + 10;
const ull bsc = 31;
char s[mxn];
ull hs[mxn];
ull bse[mxn];

void init()
{
    bse[0] = 1;
    for_(i, 1, mxn - 1)
        bse[i] = bse[i - 1] * bsc;
}

int main()
{
    /* fre(); */
    init();
    while(ss(s) && s[0] != '.')
    {
        int n = strlen(s);
        hs[n] = 0;
        rep_(i, n - 1, 0)
            hs[i] = hs[i + 1] * bsc + s[i] - 'a';

        for_(i, 1, n)
        {
            if(n % i) continue;
            int k = n / i, j;
            for(j = 0; j < n; j += i)
            {
                if(hs[0] - hs[i] * bse[i] != hs[j] - hs[j + i] * bse[i])
                    break;
            }

            if(j == n)
            {
                pr("%d\n", k);
                break;
            }
        }
    }

    return 0;
}


你可能感兴趣的:(#Hash)