TCO round 2A level3 EllysReversals

其实写代码很简单,主要是要分析清楚问题的实质,下面几点是至关重要的:

1.如果字符串是奇数长度,最后一个字符永远都保持在最后一位。

2.从0开始,每一对字母不管怎么变换都是挨在一块的,也就是说,str[0]和str[1]、str[2]和str[3]始终是相邻的。

3.如果把上述一对看成一个整体,那么通过有限步数变换,一个字符对可以跑到任何一个位置而不影响其他字符的相对顺序(最后一个位置除外)

有了以上分析,问题就简单了。一个字符串中所有字符对进行排序,然后再对所有字符串进行排序,踢出重复的就可以了。

唉,其实也不难想,但是比赛那会愣是没想出来。。。

下面的代码已经通过了system test

#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

class EllysReversals {
public:
	int getMin(vector <string>);
};

//adjacent letters will keep adjacent forever 
//except last one in odd length case
int EllysReversals::getMin(vector <string> words) {
	int len = words.size();
	for(int i=0; i<len; i++){
		vector<string> v;
		int t = words[i].size()/2;
		for(int j=0; j<t; j++){
			string str = words[i].substr(j*2, 2);
			if(str[0] > str[1]){
				char tmp = str[0];
				str[0] = str[1];
				str[1] = tmp;
			}
			v.push_back(str);		
		}
		sort(v.begin(), v.end());
		for(int j=0; j<v.size(); j++){
			words[i][j*2] = v[j][0];
			words[i][j*2+1] = v[j][1];
		}
	}
	sort(words.begin(), words.end());
	int res = 0;
	for(int i=1; i<len; i++){
		if(words[i] == words[i-1]){
			res += 2;
			i++;
		}
	}
	res = len-res;
	return res;
}

//<%:testing-code%>
//Powered by [KawigiEdit] 2.0! 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值