题解:[CSP-J 2026] 回文串 / string
题意分析
记原始展开后的字符串为 \(s\),长度为 \(L\)。
如果 \(s_i\neq s_{L-i+1}\),那么显然直接修改其中一个字符是最优的。
压缩后有 \(n\) 段,直接展开的复杂度会假掉。
考虑将一段不同的字符一起统计答案,维护双指针 \(l,r\) 表示左右指针。
如果 \(c_l\neq c_r\),肯定有一段不相同,这一段的长度为 \(k=\min(a_l,a_r)\),计入答案。
随后往里扫,令 \(a_l\leftarrow a_l-k,a_r\leftarrow a_r-k\),如果取到了 \(0\),就移动 \(l\) 或 \(r\) 往里扫即可。
时间复杂度 \(\mathcal O(n)\)。
AC 代码
//#include<bits/stdc++.h>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<iomanip>
#include<cstdio>
#include<string>
#include<vector>
#include<cmath>
#include<ctime>
#include<deque>
#include<queue>
#include<stack>
#include<list>
using namespace std;
typedef long long ll;
constexpr const int N=2e5;
int n;
ll a[N+1];
char c[N+1];
int main(){
/*freopen("test.in","r",stdin);
freopen("test.out","w",stdout);*/
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i]>>c[i];
}
int l=1,r=n;
ll ans=0;
while(l<r){
ll k=min(a[l],a[r]);
if(c[l]!=c[r]){
ans+=k;
}
a[l]-=k;
a[r]-=k;
if(!a[l]){
l++;
}
if(!a[r]){
r--;
}
}
cout<<ans<<'\n';
cout.flush();
/*fclose(stdin);
fclose(stdout);*/
return 0;
}

浙公网安备 33010602011771号