Educational Codeforces Round 64 (Rated for Div. 2) - B. Ugly Pairs - 构造法

题目传送门
思路:
首先,在字母表里面偶数位置的字符构成一个字符串s1,然后奇数位置构成一个字符串s2,这样每个字符串内部都是不相邻的了。然后将两个字符串合并时,要判断中间位置,有两种合并方法,s1+s2,s2+s1;如果这两种合并方法都不行则输出:No answer。
最后为什么是前两种不可以,就输出No answer(前面两种构造方法不行,则必然没有答案),这个可以证明。(有兴趣的可以自己证明一下,设s1的开始结尾字符为a1,b1,s2的开始结尾字符为a2,b2)

#include<bits/stdc++.h>

using namespace std;

#define pii pair<int, int>
#define mem(a,b) memset(a,b,sizeof(a))
#define per(i,a,b) for(int i=(a);i<=(b);i++)
#define rep(i,a,b) for(int i=(a);i>=(b);i--)
#define pi acos(-1.0)
#define inf 0x3f3f3f3f
#define Rand() (rand()|rand()<<15)
#define Srand() srand(time(0)^(unsigned)(unsigned long long)(new char))
typedef long long LL;
const double eps=1.0e-5;
const int maxn=200000+10;
const LL mod=1e9+7;

int n = 0,m = 0;
string s;
void solve(){
	int num[30];
	string s1,s2;
	memset(num,0,sizeof(num));
	int size = s.size();
	per(i,0,size-1){
		++num[s[i] - 'a'];
	}
	per(i,0,25){
		if(i & 1){
			while(num[i] > 0){
				s1 += ('a' + i);
				--num[i];
			}
		}else{
			while(num[i] > 0){
				s2 += ('a' + i);
				--num[i];
			}	
		}
	}
	
	if(abs(s1.back() - s2.front()) > 1){
		cout << s1 + s2 << endl;
	}else if(abs(s1.front() - s2.back()) > 1){
		cout << s2 + s1 << endl;
	}else{
		cout << "No answer" << endl;
	}
}
int main(){
	std::ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	
	int T = 0;
	cin >> T;
	while(T--){
		cin >> s;
		solve();
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值