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;
}