210413赛后总结

B:Obtaining the String

题目描述:
You are given two strings s and t. Both strings have length n and consist of lowercase Latin letters. The characters in the strings are numbered from 1 to n.

You can successively perform the following move any number of times (possibly, zero):

swap any two adjacent (neighboring) characters of s (i.e. for any i={1,2,…,n−1} you can swap si and si+1).
You can’t apply a move to the string t. The moves are applied to the string s one after another.

Your task is to obtain the string t from the string s. Find any way to do it with at most 104 such moves.

You do not have to minimize the number of moves, just find any sequence of moves of length 104 or less to transform s into t.

输入:
The first line of the input contains one integer n (1≤n≤50) — the length of strings s and t.

The second line of the input contains the string s consisting of n lowercase Latin letters.

The third line of the input contains the string t consisting of n lowercase Latin letters.

输出:
If it is impossible to obtain the string t using moves, print “-1”.

Otherwise in the first line print one integer k — the number of moves to transform s to t. Note that k must be an integer number between 0 and 104 inclusive.

In the second line print k integers cj (1≤cj<n), where cj means that on the j-th move you swap characters scj and scj+1.

If you do not need to apply any moves, print a single integer 0 in the first line and either leave the second line empty or do not print it at all.

提示:
In the first example the string s changes as follows: “abcdef” → “abdcef” → “abdcfe” → “abdfce” → “abdfec”.

In the second example there is no way to transform the string s into the string t through any allowed moves.

代码:

#include<bits/stdc++.h>
using namespace std;
#define N 100

map<char, int> mp;	//通过map容器判断两字符串是否拥有相同数量的字母
vector<int> T;		//动态数组,存入每一步交换的操作
int n;
char a[N], b[N];

int main()
{
	mp.clear();
	cin >> n;
	cin >> a >> b;
	/*利用关键字对其所映射的数值进行处理*/
	for(int i = 0; i < n; i ++){
		mp[a[i]] ++;
		mp[b[i]] --;
	}
	for(int i = 0; i < n; i ++){
		if(mp[a[i]]){			//当key对应的值不为0时说明a,b字符串每种字母数量不同,状态不合法
			cout << "-1" << endl;
			return 0;
		}
	}
	for(int i = 0; i < n; i ++){
		for(int j = i; j < n; j ++){
			if(b[i] == a[j]){		//因为要保持b不变,将a移换位置变成b,所以外层循环控制b,内层循环控制并改变a的顺序
				for(int k = j; k > i; k --){
					swap(a[k], a[k - 1]);
					T.push_back(k);		//将操作存入动态数组中
				}
				break;
			}
		}
	}
	cout << T.size() << endl;
	for(int i = 0; i < T.size(); i ++){
		printf("%s", i != 0 ? " " : "");	//使用三目运算符进行规范格式
		printf("%d",T[i]);
	}
	cout << endl;
	return 0;
}

题后总结:
1.可以用map容器判断两字符串是否除了顺序外都相同;
2.用动态数组存每一步的操作,vector< int > T;
T.push_back(x0); 将x0压入数组最后;
3.双层循环,外层控制模板,内层控制需要改变的字符串。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值