Description
Limak is a little polar bear. He likes nice strings — strings of length n, consisting of lowercase English letters only.
The distance between two letters is defined as the difference between their positions in the alphabet. For example, , and .
Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, , and .
Limak gives you a nice string s and an integer k. He challenges you to find any nice string s’ that . Find any s’ satisfying the given conditions, or print “-1” if it’s impossible to do so.
As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use gets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.
Input
The first line contains two integers n and k (1 ≤ n ≤ 105, 0 ≤ k ≤ 106).
The second line contains a string s of length n, consisting of lowercase English letters.
Output
If there is no string satisfying the given conditions then print “-1” (without the quotes).
Otherwise, print any nice string s’ that .
Sample Input
Input
4 26
bear
Output
roar
Input
2 7
af
Output
db
Input
3 1000
hey
Output
-1
题目大意
约定两个字母之间的差为两者ASCII值的差的绝对值,给定一串英文字符的字母个数n以及规定要达到的差值d,输入一个字符串s,求与这个字符串差为d的字符串
思路
用贪心从第一位开始,与’z’和’a’比较,如果用’z’或者’a’作为这一位的答案之后还是无法达到差值k,那么如果这一位与’z’的差值大就用’z’作为这一位的答案,反之用’a’,总之就是要是k减去这一位的差值要尽可能的小,然后后移一位继续贪心。如果到某一位(这一位必须小于等于n)后不满足上述条件,那么这是当前串的差值与输入的字符串的差值一定小于’z’-s[i]>=k或者s[i]-‘a’>=k,那么如果是第一种情况就用s[i]+k作为这一位的答案,反之用s[i]-k作为这一位的答案。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn=1e5+5;
int n,k;
char str[maxn];
char ans[maxn];
int main()
{
while(~scanf("%d %d",&n,&k))
{
scanf("%s",&str);
int len=strlen(str);
for(int i=0;i<len;i++)
{
if(str[i]+k>'z'&&str[i]-k<'a')
{
if('z'-str[i]>=str[i]-'a')
{
ans[i]='z';
k-='z'-str[i];
}
else
{
ans[i]='a';
k-=str[i]-'a';
}
}
else if(str[i]+k<='z')
{
ans[i]=str[i]+k;
k=0;
}
else if(str[i]-k>='a')
{
ans[i]=str[i]-k;
k=0;
}
}
if(!k) printf("%s\n",ans);
else printf("-1\n");
}
return 0;
}