CF 486C Palindrome Transformation
题目给出一个字符串和光标所在位置,每次操作可以把光标向左,向右移动或者把当前字符串ASCII值 +- 1
那么问变成回文的最小代价
首先我们观察到,因为我们可以对字符串+或者-,所以显然清理左边和右边没有任何差别,代价都是字符串的距离(这题可以改成只能+1,这样就是一道稍微难一点的题了)
然后我们假如从k开始清理,最优解显然是先清理一边的,然后拐回头清理另外一边,所以有一段路走了两次,我们维护一个前半部分有字符串不对称的最小区间,然后进行计算就好
#include <bits/stdc++.h> using namespace std; constexpr int limit = (200000 + 5);//防止溢出 #define INF 0x3f3f3f3f #define inf 0x3f3f3f3f3f #define lowbit(i) i&(-i)//一步两步 #define EPS 1e-9 #define FASTIO ios::sync_with_stdio(false);cin.tie(0),cout.tie(0); #define ff(a) printf("%d\n",a ); #define pi(a, b) pair<a,b> #define rep(i, a, b) for(ll i = a; i <= b ; ++i) #define per(i, a, b) for(ll i = b ; i >= a ; --i) #define MOD 998244353 #define traverse(u) for(int i = head[u]; ~i ; i = edge[i].next) #define FOPEN freopen("C:\\Users\\tiany\\CLionProjects\\akioi\\data.txt", "rt", stdin) #define FOUT freopen("C:\\Users\\tiany\\CLionProjects\\akioi\\dabiao.txt", "wt", stdout) typedef long long ll; typedef unsigned long long ull; char buf[1 << 23], *p1 = buf, *p2 = buf, obuf[1 << 23], *O = obuf; inline ll read() { #define getchar() (p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++) ll sign = 1, x = 0; char s = getchar(); while (s > '9' || s < '0') { if (s == '-')sign = -1; s = getchar(); } while (s >= '0' && s <= '9') { x = (x << 3) + (x << 1) + s - '0'; s = getchar(); } return x * sign; #undef getchar }//快读 void print(ll x) { if (x / 10) print(x / 10); *O++ = x % 10 + '0'; } void write(ll x, char c = 't') { if (x < 0)putchar('-'), x = -x; print(x); if (!isalpha(c))*O++ = c; fwrite(obuf, O - obuf, 1, stdout); O = obuf; } int n, m, k; int a[limit]; int min_step(char c, char ch){//price from c to ch return min(abs(c - ch), 26 - abs(c - ch)); } int min_step2(int idx, int idx2){ return min(abs(idx - idx2), n - abs(idx - idx2)); } struct node{ int idx; int val; bool operator < (const node &b) const{ return val > b.val; } }; void solve(){ cin>>n; cin>>k; string s; cin>>s; s = " " + s; int l,r; ll ans = INF; ll res = 0; //跟k没关系,我们只需要知道清除左半边和右半边的东西给的代价 l = -1, r = -1; rep(i,1,(n + 1) / 2){ ll tmp = min_step(s[i], s[n - i + 1]); res += tmp; //代价是一样的 if(tmp){ if(l == -1)l = i; r = i; } } if(r == -1){ cout<<0<<endl; return; } if(k > (n + 1) / 2){ k = n - k + 1; //对称 } ll cost = min({min_step2(k, l), min_step2(k, r)}); cost += abs(r - l); cout<<res + cost<<endl; }; int32_t main() { #ifdef LOCAL FOPEN; // FOUT; #endif FASTIO // int kase; // cin>>kase; // while (kase--) solve(); cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << "s\n"; return 0; }
天才选手zerol的主页:https://zerol.me/
|
WeepingDemon的个人主页:https://weepingdemon.gitee.io/blog/