Codeforces CF#628 Education 8 C. Bear and String Distance
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,然后全部一样即可。
1 #include <cstdio> 2 #include <cstring> 3 #include <string> 4 #include <iostream> 5 #include <algorithm> 6 using namespace std; 7 8 const int N = 100010; 9 int n, k; 10 char str[N]; 11 char ans[N]; 12 13 int main() { 14 scanf("%d%d", &n, &k); 15 scanf("%s", str); 16 memset(ans, 0, sizeof(ans)); 17 for(int i = 0; i < n; ++i) { 18 int dis = min(k, max(str[i] - 'a', 'z' - str[i])); 19 if(str[i] - 'a' >= dis) ans[i] = str[i] - dis; 20 else ans[i] = str[i] + dis; 21 k -= dis; 22 } 23 if(k) puts("-1"); 24 else printf("%s\n", ans); 25 return 0; 26 }