Square Distance
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 312 Accepted Submission(s): 102
Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different.
Peter has a string s=s1s2...sn of even length. He wants to find a lexicographically smallest square string t=t1t2...tn that the hamming distance between s and tis exact m. In addition, both s and t should consist only of lowercase English letters.
The first contains two integers n and m (1≤n≤1000,0≤m≤n,n is even) -- the length of the string and the hamming distance. The second line contains the string s.
#
3 4 1 abcd 4 2 abcd 4 2 abab
Impossible abab aaaa
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
#include <vector>
#include <string>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define L(i) i<<1
#define R(i) i<<1|1
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-9
#define maxn 10010
#define MOD 1000000007
const int mod = 2520;
int gcd(int a, int b)
{
while(b)
{
int t = a % b;
a = b;
b = t;
}
return a;
}
int T,n,m;
int sum[550];
char st[1200];
char re[1200];
int main()
{
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
scanf("%s",&st);
int tt=0;
memset(sum,0,sizeof(sum));
for(int i=0;i<n/2;i++)
{
if(st[i]!=st[i+n/2]) tt++;
sum[i] = tt;
}
if(tt>m) {printf("Impossible\n");continue;}
int ff=0;
bool flag=true;
for(int i=0;i<n/2;i++)
{
int tmp=0,uu,oo;
re[i] = 'a';
if(re[i]!=st[i]) tmp++;
if(re[i]!=st[i+n/2]) tmp++;
uu=ff+tmp+sum[n/2-1] - sum[i];
oo=ff+tmp+ (n/2-1 - i)*2;
if(uu<=m&&oo>=m)
{
ff+=tmp;
continue;
}
tmp=0;
re[i] = 'b';
if(re[i]!=st[i]) tmp++;
if(re[i]!=st[i+n/2]) tmp++;
uu=ff+tmp+sum[n/2-1] - sum[i];
oo=ff+tmp+ (n/2-1 - i)*2;
if(uu<=m&&oo>=m)
{
ff+=tmp;
continue;
}
tmp=0;
re[i] = 'c';
if(re[i]!=st[i]) tmp++;
if(re[i]!=st[i+n/2]) tmp++;
uu=ff+tmp+sum[n/2-1] - sum[i];
oo=ff+tmp+ (n/2-1 - i)*2;
if(uu<=m&&oo>=m)
{
ff+=tmp;
continue;
}
tmp=0;
re[i] =min(st[i],st[i+n/2]);
if(re[i]!=st[i]) tmp++;
if(re[i]!=st[i+n/2]) tmp++;
uu=ff+tmp+sum[n/2-1] - sum[i];
oo=ff+tmp+ (n/2-1 - i)*2;
if(uu<=m&&oo>=m)
{
ff+=tmp;
continue;
}
flag=false;
// printf("hkfghfkhg\n");
}
if(flag==false)
{
printf("Impossible\n");continue;
}
for(int i=0;i<n/2;i++)
{
printf("%c",re[i]);
}
for(int i=0;i<n/2;i++)
{
printf("%c",re[i]);
}
printf("\n");
}
return 0;
}