问题描述
给定一个有n个数字的序列,记作{an},需要进行k次操作,每次操作找到最小的x使得a(x)=2,a(x+1)=3,如果x为奇数,则令d(x+1)=2,反之令d(x)=3,若没有这样的x则数字不变。
求k此操作之后原数列会变成什么
输入
本题有多组数据。
每组数据第一行是两个正整数n,k分别表示数字个数和操作次数
第二行有n个数字,数字之间没有空格
输出
对每组数据输出一行为最终的数列
样例输入
7 2
2343223
4 1
2234
样例输出
2243233
2334
算法讨论
显然直接暴力模拟会超时,我们自己手推一下会发现以下规律:当223这一串数字的第一个2在奇数位上时,它会在223和233之间循环,当操作数为奇数时就是233,偶数时就是223;233时同理。那么我们找出这两个循环后,剩下的普通情况直接模拟就好了。
var
i,n,k:longint;
st:ansistring;
function check1(x:longint):boolean;
begin
if (x mod 2=1) and (st[x]='2') and (st[x+1]='2') and (st[x+2]='3')
then exit(true)
else exit(false);
end;
function check2(x:longint):boolean;
begin
if (x mod 2=1) and (st[x]='2') and (st[x+1]='3') and (st[x+2]='3')
then exit(true)
else exit(false);
end;
begin
// assign(input,'data1.in'); reset(input);
// assign(output,'change.out'); rewrite(output);
while not(eof) do
begin
readln(n,k);
readln(st);
for i:=1 to n do
begin
if k=0
then break;
if check1(i) then
begin
if (k mod 2=1) then
st[i+1]:='3';
break;
end;
if check2(i) then
begin
if (k mod 2=1) then
st[i+1]:='2';
break;
end;
if (st[i]='2') and (st[i+1]='3') and (i mod 2=1)
then begin
st[i+1]:='2';
dec(k);
end
else if (st[i]='2') and (st[i+1]='3') and (i mod 2=0)
then begin
st[i]:='3';
dec(k);
end;
end;
writeln(st);
end;
end.
Pixiv ID:61432734