【CodeForces - 628C】Bear and String Distance(贪心,构造)
生活随笔
收集整理的這篇文章主要介紹了
【CodeForces - 628C】Bear and String Distance(贪心,构造)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Description?
定義兩個(gè)小寫(xiě)字母之間的距離為這兩個(gè)字母在字母表中的距離,如dis(a,z)=25,dis(a,c)=2,兩個(gè)長(zhǎng)度相同串的距離為這兩個(gè)串對(duì)應(yīng)位置字母距離之和。現(xiàn)給出一個(gè)長(zhǎng)度為n的串s和一個(gè)距離k,問(wèn)是否存在一個(gè)長(zhǎng)度為n的串ss,使得dis(s,ss)=k,如果存在任意輸出一解,如果不存在則輸出-1?
Input?
第一行為兩個(gè)整數(shù)n,k(1<=n<=10^5,1<=k<=10^6),第二行為一長(zhǎng)度為n的僅包含小寫(xiě)字母的字符串?
Output?
如果存在一個(gè)長(zhǎng)度為n的串ss,使得dis(s,ss)=k則輸出ss,如果不存在則輸出-1?
Sample Input?
4 26?
bear?
Sample Output?
roar?
解題報(bào)告:
直接貪心即可,超過(guò)m的就讓他變?yōu)閍,沒(méi)超過(guò)m的就讓他變?yōu)閦,注意可能是變不到極端,k就=0了,所以需要特判一下。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n,k; char s[MAX],ans[MAX]; int main() {cin>>n>>k;cin>>s+1;for(int i = 1; i<=n; i++) {if(k) {if(s[i] <= 'm') ans[i] = min(s[i] + k,(int)'z'),k -= ans[i] - s[i];else ans[i] = max(s[i]-k,(int)'a'),k -= s[i] - ans[i];}else ans[i] = s[i];}ans[n+1]=0;if(k) puts("-1");else printf("%s\n",ans+1);return 0 ; }?
總結(jié)
以上是生活随笔為你收集整理的【CodeForces - 628C】Bear and String Distance(贪心,构造)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 影像脱胎换骨 曝Redmi要用旗舰大底主
- 下一篇: 【HDU - 6081】度度熊的王国战略