Welcome to another task about breaking the code lock! Explorers Whitfield and Martin came across an unusual safe, inside of which, according to rumors, there are untold riches, among which one can find the solution of the problem of discrete logarithm!
Of course, there is a code lock is installed on the safe. The lock has a screen that displays a string of n lowercase Latin letters. Initially, the screen displays string s. Whitfield and Martin found out that the safe will open when string t will be displayed on the screen.
The string on the screen can be changed using the operation «shift x». In order to apply this operation, explorers choose an integer xfrom 0 to n inclusive. After that, the current string p = αβ changes to βRα, where the length of β is x, and the length of α is n - x. In other words, the suffix of the length x of string p is reversed and moved to the beginning of the string. For example, after the operation «shift4» the string «abcacb» will be changed with string «bcacab », since α = ab, β = cacb, βR = bcac.
Explorers are afraid that if they apply too many operations «shift», the lock will be locked forever. They ask you to find a way to get the string t on the screen, using no more than 6100 operations.
The first line contains an integer n, the length of the strings s and t (1 ≤ n ≤ 2 000).
After that, there are two strings s and t, consisting of n lowercase Latin letters each.
If it is impossible to get string t from string s using no more than 6100 operations «shift», print a single number - 1.
Otherwise, in the first line output the number of operations k (0 ≤ k ≤ 6100). In the next line output k numbers xi corresponding to the operations «shift xi» (0 ≤ xi ≤ n) in the order in which they should be applied.
6 abacbb babcba
4 6 3 2 3
3 aba bba
-1
In the first example, after applying the operations, the string on the screen will change as follows:
- abacbb bbcaba
- bbcaba ababbc
- ababbc cbabab
- cbabab babcba
题意:给你一个初始串和一个目标串,每次的操作只有一种,设定一个x,让后x个字符翻转并接在原串的前边,问你能否在6100次操作内使得原串变成目标串,如果可以就输出操作过程,否则输出-1
题解:学习了http://blog.csdn.net/jaihk662/article/details/79382120的方法,感觉很巧,每次将当前要匹配的字符给加在后边,这样的暴力构造保证了只要是在有解的情况下,一定可以在6000次内构造出来。。。
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
char s1[2005],s2[2005],s3[2005];
int n,ans[6005],len;
void work(int x)
{
int l=x,r=n;
while(l<=r)
swap(s1[l],s1[r]),l++,r--;
for(int i=1,j=x;j<=n;i++,j++)
s3[i]=s1[j];
for(int i=n-x+2,j=1;i<=n;i++,j++)
s3[i]=s1[j];
for(int i=1;i<=n;i++)
s1[i]=s3[i];
ans[++len]=n-x+1;
}
int main(void)
{
int i,j;
scanf("%d",&n);
scanf("%s%s",s1+1,s2+1);
for(i=1;i<=n;i++)
{
for(j=1;j<=n-i+1;j++)
if(s1[j]==s2[i])
break;
if(j==n-i+2)
{
printf("-1\n");
return 0;
}
work(j+1);work(n);work(2);
}
printf("%d\n",len);
for(int i=1;i<=len;i++)
printf("%d ",ans[i]);
printf("\n");
return 0;
}