1 second
256 megabytes
standard input
standard output
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 usegets/scanf/printf instead of getline/cin/cout in C++, prefer to use BufferedReader/PrintWriter instead ofScanner/System.out in Java.
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.
If there is no string satisfying the given conditions then print "-1" (without the quotes).
Otherwise, print any nice string s' that .
4 26
bear
roar
2 7
af
db
3 1000
hey
-1
题意:
给出一个长度为n的字符串,定义两个字符串的距离就是对应位的字母在字母表上的距离之和,也就是ae跟ea距离为4+4=8。
给出k,要求构造一个等长的字母串,使得两串距离恰好为k。
题解:
很容易想到每一位都尽量拉长距离,尽快达到k,然后全部一样即可。
#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std; const int N = ;
int n, k;
char str[N];
char ans[N]; int main() {
scanf("%d%d", &n, &k);
scanf("%s", str);
memset(ans, , sizeof(ans));
for(int i = ; i < n; ++i) {
int dis = min(k, max(str[i] - 'a', 'z' - str[i]));
if(str[i] - 'a' >= dis) ans[i] = str[i] - dis;
else ans[i] = str[i] + dis;
k -= dis;
}
if(k) puts("-1");
else printf("%s\n", ans);
return ;
}