#include <bits/stdc++.h> using namespace std; const long long P = 1000000007, p1 = 37, inv1 = 621621626, maxp1 = 481251275, p2 = 41, inv2 = 658536590, maxp2 = 707000835; long long fastpow(long long p, long long k) { long long odp = 1, mult = p; while(k) { if(k & 1) odp = odp * mult % P; k >>= 1; mult = mult * mult % P; } return odp; } int main() { cin.tie(NULL); cout.tie(NULL); int n; cin >> n; int i = 0, a = getchar(); long long h1 = 0, h2 = 0, g1 = 0, g2 = 0, pow1 = 1, pow2 = 1, div1 = maxp1, div2 = maxp2; while(true) { a = getchar(); if(a == '\n') break; h1 = (h1 + (a - 'a' + 1) * pow1) % P; g1 = (g1 + (a - 'a' + 1) * pow2) % P; h2 = (h2 + (a - 'a' + 1) * div1) % P; g2 = (g2 + (a - 'a' + 1) * div2) % P; pow1 = pow1 * p1 % P; pow2 = pow2 * p2 % P; div1 = div1 * inv1 % P; div2 = div2 * inv2 % P; ++i; } if(h1 * fastpow(p1, 20000000 - i + 1) % P == h2 && g1 * fastpow(p2, 20000000 - i + 1) % P == g2) cout << "TAK" << endl; else cout << "NIE" << endl; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | #include <bits/stdc++.h> using namespace std; const long long P = 1000000007, p1 = 37, inv1 = 621621626, maxp1 = 481251275, p2 = 41, inv2 = 658536590, maxp2 = 707000835; long long fastpow(long long p, long long k) { long long odp = 1, mult = p; while(k) { if(k & 1) odp = odp * mult % P; k >>= 1; mult = mult * mult % P; } return odp; } int main() { cin.tie(NULL); cout.tie(NULL); int n; cin >> n; int i = 0, a = getchar(); long long h1 = 0, h2 = 0, g1 = 0, g2 = 0, pow1 = 1, pow2 = 1, div1 = maxp1, div2 = maxp2; while(true) { a = getchar(); if(a == '\n') break; h1 = (h1 + (a - 'a' + 1) * pow1) % P; g1 = (g1 + (a - 'a' + 1) * pow2) % P; h2 = (h2 + (a - 'a' + 1) * div1) % P; g2 = (g2 + (a - 'a' + 1) * div2) % P; pow1 = pow1 * p1 % P; pow2 = pow2 * p2 % P; div1 = div1 * inv1 % P; div2 = div2 * inv2 % P; ++i; } if(h1 * fastpow(p1, 20000000 - i + 1) % P == h2 && g1 * fastpow(p2, 20000000 - i + 1) % P == g2) cout << "TAK" << endl; else cout << "NIE" << endl; } |