P11190 「KDOI-10」反回文串 题解
一个自我感觉很聪明的方法。
发现非回文串长度至少为
而长度为
而最后可能会剩下
这里的处理方式是有很多种的,这里讲一下我自认为一个很好写的方法。我们在归纳一种字符在字符串中出现位置时将其随机打乱一下。这样每次执行操作时得到的具体方案都是不同的,重复个
Code
#include<bits/stdc++.h>
using namespace std;
#define pii pair<int, int>
const int N = 1e5 + 7;
int Case, Task;
int n;
string s;
vector<int>g[30];
int w[30];
priority_queue<pii>q;
vector<int>ans[N];
int cnt;
void Out(){
printf("Huoyu\n%d\n", cnt);
for(int i = 1; i <= cnt; i++){
sort(ans[i].begin(), ans[i].end());
printf("%d ", ans[i].size());
for(int j : ans[i]){
printf("%d ", j);
}
puts("");
}
}
void Init(){
for(int i = 0; i < 26; i++){
g[i].clear();
w[i] = 0;
}
while(!q.empty()) q.pop();
for(int i = 1; i <= n; i++){
ans[i].clear();
}
cnt = 0;
}
bool check(vector<int>f){
int i = 0, j = f.size() - 1;
while(i <= j){
if(s[f[i]] != s[f[j]]) return true;
else i++, j--;
}
return false;
}
bool Main(){
Init();
for(int i = 1; i <= n; i++) g[s[i] - 'a'].push_back(i);
for(int c = 0; c < 26; c++){
int len = g[c].size();
w[c] = len;
for(int i = 1; i <= len; i++){ //随机打乱
int x = rand() % len, y = rand() % len;
swap(g[c][x], g[c][y]);
}
if(w[c]) q.push(make_pair(w[c], c));
}
while(q.size() > 1){
int u = q.top().second;
q.pop();
int v = q.top().second;
q.pop();
++cnt;
ans[cnt].push_back(g[u][--w[u]]);
ans[cnt].push_back(g[v][--w[v]]);
if(w[u]) q.push(make_pair(w[u], u));
if(w[v]) q.push(make_pair(w[v], v));
}
if(!cnt){
return 0;
}
if(q.empty()){
return 1;
}
else{
int c = q.top().second;
for(int i = 1; i <= q.top().first; i++){
ans[cnt].push_back(g[c][--w[c]]);
}
sort(ans[cnt].begin(), ans[cnt].end());
return check(ans[cnt]);
}
}
int main(){
srand(time(0));
ios::sync_with_stdio(0);
cin.tie(0);
cin >> Case >> Task;
while(Task--){
cin >> n >> s;
s = '$' + s;
bool flg = 0;
for(int i = 1; i <= 30; i++){
flg = Main();
if(flg){
Out();
break;
}
}
if(!flg) printf("Shuiniao\n");
}
return 0;
}