0
点赞
收藏
分享

微信扫一扫

【CodeForces - 628C】Bear and String Distance(贪心,构造)

gy2006_sw 2022-06-15 阅读 55

Description 
定义两个小写字母之间的距离为这两个字母在字母表中的距离,如dis(a,z)=25,dis(a,c)=2,两个长度相同串的距离为这两个串对应位置字母距离之和。现给出一个长度为n的串s和一个距离k,问是否存在一个长度为n的串ss,使得dis(s,ss)=k,如果存在任意输出一解,如果不存在则输出-1 
Input 
第一行为两个整数n,k(1<=n<=10^5,1<=k<=10^6),第二行为一长度为n的仅包含小写字母的字符串 
Output 
如果存在一个长度为n的串ss,使得dis(s,ss)=k则输出ss,如果不存在则输出-1 
Sample Input 
4 26 
bear 
Sample Output 
roar 

解题报告:

直接贪心即可,超过m的就让他变为a,没超过m的就让他变为z,注意可能是变不到极端,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 ;
}

 


举报

相关推荐

0 条评论