最小表示法+hash hdu2609 How many

传送门:点击打开链接

题意:有n个串,每个串是一个环,如果通过移动环之后能一样,认为是同一种串。问有多少种串。

思路:很明显我们首先要把认为是一样的串变成一样的,比如找到这个串的最小表示法,所以这道题的目的就是为了求最小表示法,然后用hash搞一搞排序然后去重,或者是直接插入到set里面取size都是可以的

KMP(复杂度O(n))来搞最小表示法暂时还不会,先挖个坑,我这里还有一种通过二分+hash求lcp来求最小表示法的思路,复杂度O(nlogn),先凑合着用把

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout << "[" << x << "]"
#define FIN freopen("input.txt", "r", stdin)
#define FOUT freopen("output.txt", "w+", stdout)
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
typedef unsigned long long ULL;

const int MX = 3e2 + 5;
const int INF = 0x3f3f3f3f;
const int seed = 131;

ULL fac[MX], pre[MX], S[10005];
char A[MX];
void presolve() {
    fac[0] = 1;
    for(int i = 1; i < MX; i++) {
        fac[i] = fac[i - 1] * seed;
    }
}
bool check(int a, int b, int l) {
    ULL left = pre[a + l - 1] - pre[a - 1] * fac[l];
    ULL right = pre[b + l - 1] - pre[b - 1] * fac[l];
    return left == right;
}
int lcp(int n, int a, int b) {
    int l = 0, r = n, m;
    while(l <= r) {
        m = (l + r) >> 1;
        if(check(a, b, m)) l = m + 1;
        else r = m - 1;
    }
    return l - 1;
}
ULL change() {
    int n = strlen(A + 1);
    for(int i = 1; i <= n; i++) {
        A[n + i] = A[i];
    }
    pre[0] = 0;
    for(int i = 1; i <= 2 * n; i++) {
        pre[i] = pre[i - 1] * seed + A[i];
    }
    int ans = 1, m;
    for(int i = 1; i <= n; i++) {
        int l = lcp(n, ans, i);
        if(A[i + l] < A[ans + l]) ans = i;
    }
    ULL ret = 0;
    for(int i = ans, j = 1; j <= n; i++, j++) {
        ret = ret * seed + A[i];
    }
    return ret;
}
int main() {
    int n; //FIN;
    presolve();
    while(~scanf("%d", &n)) {
        for(int i = 1; i <= n; i++) {
            scanf("%s", A + 1);
            S[i] = change();
        }
        sort(S + 1, S + 1 + n);
        int sz = unique(S + 1, S + 1 + n) - S - 1;
        printf("%d\n", sz);
    }
    return 0;
}


你可能感兴趣的:(最小表示法+hash hdu2609 How many)