CodeForces 628C
Description
Limak is a little polar bear. He likes nice strings — strings of lengthn, consisting of lowercase English letters only.
The distance between two letters is defined as the difference between their positions in the alphabet. For example, dist(c,e)=dist(e,c)=2;, and .dist(a,z)=dist(z,a)=25
Also, the distance between two nice strings is defined as the sum of distances of corresponding letters. For example, dist(af,db)=dist(a,d)+dist(f,b)=3+4=7, and dist(bear,roar)=16+10+0+0=26.
Limak gives you a nice string s and an integerk. He challenges you to find any nice strings' that dist(s,s’)=k . 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.
Input
The first line contains two integers n andk (1 ≤ n ≤ 105,0 ≤ k ≤ 106).
The second line contains a string s of lengthn, 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 dist(s,s’)=k .
Sample Input
4 26 bear
roar
2 7 af
db
3 1000 hey
-1
题意:两个字符串比对,两个字符串相同的位置上的字符的Ascall码值的差值的绝对值的和。现在已知其中的一个字符串和差值总和m,求另一个字符串(有多个输出其中任意一个字符串)。
思路:从第一个字符开始找到与他差值最大的字符’a‘或'z,并记录下来,存在ans数组中,然后从总和m中减去当前字符的最大差值path,依次往下进行。当m<path时,让当前字符加上m即可得到当前位待求字符,剩下的待求字符和已知字符串剩下的字符相同即可。若字符串全部找到后,m仍然大于0,则说明不可能找到待求字符串与已知字符串的差值和等于m.
My solution:/*2016.4.22*/
#include<string.h>
#include<stdio.h>
#include<algorithm>
using namespace std;
char c[100100],ans[100100];
int path,n,m;
int solve(char b)//计算当前字符所能得到的最大差值
{
int x,y;
x=b-'a';//与字符‘a’比较得到差值
y='z'-b;//与字符‘z’比较得到差值
if(y<0)
y=-1*y;
if(y>x)//取最大差值的字符(标记)进行返回,path则记录最大差值
{
path=y;
return 1;
}
else
{
path=x;
return 0;
}
}
int main()
{
int i,j,k,h;
while(scanf("%d%d",&n,&m)==2)
{
scanf("%s",c);
for(i=0;i<n;i++)
{
path=0;
k=solve(c[i]);//k用来标识最大差值字符是a,还是z
if(path<=m)//当前差值小于差值和
{
if(k==1)//最大差值字符是z
{
ans[i]='z';//记录该位的字符
m-=path;//更新剩余差值和
}
else//最大差值字符是a
{
ans[i]='a';//记录该位的字符
m-=path;
}
}
else//当前最大差值小于差值和
{
if(k==1)//最大差值是由字符z得到,现在差值用不完
{
ans[i]=c[i]+m;//即可得待求字符
m=0;//更新m值
}
else//最大差值是由字符a得到
{
ans[i]=c[i]-m;
m=0;
}
i++;
break;
}
}
for(;i<n;i++)//当i<n时,差值和已经匹配完了 ,剩余差值和为0,即剩余的待求字符与剩余的已知字符相同
ans[i]=c[i];
if(m>0)//无法找到合适的字符串
printf("-1\n");
else
{
ans[n]='\0';//字符串最后一位应为'\0'
printf("%s\n",ans);
}
}
return 0;
}