tepyotin2

Queries for Number of Palindromes

Jul 10th, 2025
623
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4.  
  5. using namespace std;
  6.  
  7. void fast_io() {
  8.     ios_base::sync_with_stdio(false);
  9.     cin.tie(NULL);
  10. }
  11.  
  12. int main() {
  13.     fast_io();
  14.  
  15.     string s;
  16.     cin >> s;
  17.  
  18.     int n = s.length();
  19.  
  20.     vector<vector<bool>> is_palindrome(n, vector<bool>(n, false));
  21.  
  22.     for (int len = 1; len <= n; ++len) {
  23.         for (int i = 0; i <= n - len; ++i) {
  24.             int j = i + len - 1;
  25.             if (len == 1) {
  26.                 is_palindrome[i][j] = true;
  27.             } else if (len == 2) {
  28.                 is_palindrome[i][j] = (s[i] == s[j]);
  29.             } else {
  30.                 is_palindrome[i][j] = (s[i] == s[j] && is_palindrome[i+1][j-1]);
  31.             }
  32.         }
  33.     }
  34.  
  35.     vector<vector<int>> count(n, vector<int>(n, 0));
  36.    
  37.     for (int len = 1; len <= n; ++len) {
  38.         for (int i = 0; i <= n - len; ++i) {
  39.             int j = i + len - 1;
  40.             if (len == 1) {
  41.                 count[i][j] = 1;
  42.             } else if (len == 2) {
  43.                 count[i][j] = is_palindrome[i][j] + 2;
  44.             } else {
  45.                 count[i][j] = count[i+1][j] + count[i][j-1] - count[i+1][j-1];
  46.                 count[i][j] += is_palindrome[i][j];
  47.             }
  48.         }
  49.     }
  50.  
  51.     int q;
  52.     cin >> q;
  53.     while (q--) {
  54.         int l, r;
  55.         cin >> l >> r;
  56.         cout << count[l - 1][r - 1] << " ";
  57.     }
  58.     cout << endl;
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment