Ural 1989 (tree-like array + polynomial hash)

Source: Internet
Author: User

Test instructions: Given a string, there are two operations, one is p a B, the string from position A to the substring of position B is a palindrome substring, the other operation c a B, the character of the string position A is replaced by B.

Solution: Because the string length is 1e5 and the number of times to ask also has 1e5, so the violence must be timed out, and then consider using a tree array to maintain the hash value of the string to solve, two operations with positive and negative direction of the interval ratio of the hash value and a single point modification.

#include <cstdio> #include <cstring> #include <algorithm> #define ULL unsigned long longusing namespace std;const int n = 100005;int n, m, L, R, Pos;char Str[n], q[20], C; ULL c[n][2], hash[n];int lowbit (int x) {return x & (-X);} ULL Sum (int x, int y) {ULL ret = 0;while (x > 0) {ret + c[x][y];x-= lowbit (x);} return ret;} void Add (int x, ULL d, int y) {while (x <= N) {c[x][y] + = d;x + = lowbit (x);}} int main () {hash[0] = 1;for (int i = 1; i < N; i++) hash[i] = hash[i-1] * 27;//are lowercase while (scanf ("%s", str) = = 1) {Me Mset (c, 0, sizeof (c)), n = strlen (str), for (int i = 0; i < n; i++) {ADD (i + 1, (Str[i]-' a ') * Hash[i], 0); ADD (i + 1, (Str[n-i-1]-' a ') * hash[i], 1);} scanf ("%d", &m), while (m--) {scanf ("%s", Q), if (q[0] = = ' P ') {scanf ("%d%d", &l, &r); ULL H1 = (sum (r, 0)-sum (l-1, 0)) * Hash[n-r]; ULL h2 = (SUM (n-l + 1, 1)-SUM (n-r, 1)) * HASH[L-1];IF (H1 = H2) printf ("yes\n"); elseprintf ("no\n");} else {scanf ("%d%c", &pos, &c);T x = c-str[pos-1]; ADD (POS, x * hash[pos-1], 0); ADD (N-pos + 1, x * Hash[n-pos], 1); str[pos-1] = C;}}} return 0;}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Ural 1989 (tree-like array + polynomial hash)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.