传送门:http://codeforces.com/contest/1015/problem/B
题意:
给定一个s序列和一个t序列,二者长度相同,判断s序列是否能够通过若干次的相邻元素交换,得到t序列,可以则输出交换次数和每次变换时左边元素的位置,否则输出-1。
思路:
遍历t序列,对于每个t[i],找到j>i,满足s[j]=t[i](找不到就输出-1),记录s[j]移动到i位置的每次操作。
参考资料http://codeforces.com/blog/entry/60949
参考代码:
#include<iostream>
#include<string>
#include<cstdio>
#include<queue>
#include<stack>
#include<vector>
#include<string.h>
#include<algorithm>
#define N 100+5
using namespace std;
int a[N];
int main()
{
int n;
string s,t;
cin >> n >> s >> t;
vector<int> ans;
for(int i = 0; i < n; i++)
{
if(s[i] == t[i]) continue; //元素无需变换,继续遍历
int pos = -1;
for(int j = i + 1; j < n; j++)
{
if(s[j] == t[i])
{
pos = j;
break;
}
}
if(pos == -1)
{
cout << -1;
break;
}
else
{
for (int j = pos - 1; j >= i; j--)
{
swap(s[j], s[j + 1]);
ans.push_back(j); //记录每次变换的情况
}
}
}
if(s == t)
{
cout << ans.size() << endl;
//切记题目说明下标从1开始
for(int i = 0; i < ans.size(); i++) cout << ans[i] + 1 << ' ';
}
}