标签:codeforces
给定半回文子串的定义,现给你一个串S和一个整数K,输出S所有子串中且是半回文排名第K的子串,半回文子串按照字典序升序顺序。(len(S) <= 5000)
#include<bits\stdc++.h> #define MAX_ASCII 2 using namespace std; const int N = 5e+3 + 7; bool dp[N][N]; char str[N]; int dict[N * N][MAX_ASCII + 1], cnt = 1; //字典树插入 void Insert(const char *s, int L, int R) { int v = 0, i = L; while (L <= R) { if (dict[v][s[L] - 'a']) v = dict[v][s[L++] - 'a']; else v = dict[v][s[L++] - 'a'] = cnt++; if (dp[i][L - 1]) ++dict[v][2]; } } //先序遍历查询第K大值 bool Rank(int v, vector<char> &path, int &k) { k -= dict[v][2]; if (k <= 0) { for (auto x : path) cout << x; cout << endl; return true; } for (int i = 0; i < 2; ++i) { if (dict[v][i]) { path.push_back((char)(i + 'a')); if (Rank(dict[v][i], path, k)) return true; path.pop_back(); } } return false; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int k, len; cin >> str >> k; len = strlen(str); for (int i = len - 1; i >= 0; --i) for (int j = len - 1; j >= i; --j) dp[i][j] = i <= j - 4 ? (str[i] == str[j] && dp[i + 2][j - 2]) : str[i] == str[j]; for (int i = 0; i < len; ++i) { int j = len - 1; for (; j >= i && !dp[i][j]; --j); Insert(str, i, j); } vector<char> path; Rank(0, path, k); return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
Codeforces 311(div 2):E. Ann and Half-Palindrome
标签:codeforces
原文地址:http://blog.csdn.net/dream_you_to_life/article/details/46802147