标签:har cab possible hash else sof 组成 sample ==
题目描述
输入
输出
样例输入
Sample Input1:
7
ABXCABC
Sample Input2:
6
ABCDEF
Sample Input3:
9
ABABABABA
样例输出
Sample Output1:
ABC
Sample Output2:
NOT POSSIBLE
Sample Output3:
NOT UNIQUE
题解
字符串hash
首先偶数长度一定不存在,输出NOT POSSIBLE
奇数则先将每个前缀的hash值求出来,然后枚举多余字符位置,并根据位置与n/2和n/2+1的关系判断并求出前后两个字符串的hash值。
然后hash值相同时比较一下就好了。
#include <cstdio> #define N 2000010 char str[N]; unsigned long long hash[N] , base[N] , x , y , ans; int main() { int n , i , p , flag = 0 , sum = 0; scanf("%d%s" , &n , str + 1); if(n % 2 == 0) { printf("NOT POSSIBLE\n"); return 0; } base[0] = 1; for(i = 1 ; i <= n ; i ++ ) hash[i] = hash[i - 1] * 131 + str[i] , base[i] = base[i - 1] * 131; for(i = 1 ; i <= n ; i ++ ) { if(i <= n / 2) x = hash[n / 2 + 1] - hash[i] * base[n / 2 - i + 1] + hash[i - 1] * base[n / 2 - i + 1]; else x = hash[n / 2]; if(i <= n / 2 + 1) y = hash[n] - hash[n - n / 2] * base[n / 2]; else y = (hash[i - 1] - hash[n / 2] * base[i - n / 2 - 1]) * base[n - i] + hash[n] - hash[i] * base[n - i]; if(x == y) { if(flag && ans != x) { printf("NOT UNIQUE\n"); return 0; } flag = 1 , ans = x , p = i; } } if(!flag) { printf("NOT POSSIBLE\n"); return 0; } for(i = 1 ; sum < n / 2 ; i ++ ) if(i != p) printf("%c" , str[i]) , sum ++ ; printf("\n"); return 0; }
【bzoj3916】[Baltic2014]friends 字符串hash
标签:har cab possible hash else sof 组成 sample ==
原文地址:http://www.cnblogs.com/GXZlegend/p/6871534.html