CodeForces 思维题集锦 #3 - 1156B (1800)
本文是我的 CF 思维题集锦的第三期,点我返回索引。
原题链接:1156B Ugly Pairs (dfs and similar, greedy, implementation, sortings, strings, *1800)
题意简述
对字符串进行排序,使相邻的两个字母在字母表不相邻。
解法分析
考虑当字符的奇偶性相同时一定可以排到一块,因此我们按照 a 到当前字符的偏移量的奇偶性将原字符串拆分为两个,并分别进行排序。然后将这两个字符串首尾相接,判断是否符合要求即可。
代码很短也很好写。
代码
//By: Luogu@rui_er(122461)
#include <bits/stdc++.h>
#define loop while(true)
#define rep(x,y,z) for(int x=y;x<=z;x++)
#define per(x,y,z) for(int x=y;x>=z;x--)
#define fil(x,y) memset(x, y, sizeof(x))
#define mulT0 int T; for(scanf("%d", &T);T;T--)
#define mulT1 int T, rnds; for(scanf("%d", &T),rnds=1;rnds<=T;rnds++)
using namespace std;
typedef long long ll;
const int N = 105;
char s[N], a[N], b[N];
int main() {
mulT0 {
scanf("%s", s+1);
int n = strlen(s+1), LA = 0, LB = 0;
rep(i, 1, n) {
if((s[i] - 'a') & 1) a[++LA] = s[i];
else b[++LB] = s[i];
}
a[LA+1] = b[LB+1] = '\0';
sort(a+1, a+1+LA);
sort(b+1, b+1+LB);
if(abs(a[LA] - b[1]) != 1) printf("%s%s\n", a+1, b+1);
else if(abs(b[LB] - a[1]) != 1) printf("%s%s\n", b+1, a+1);
else puts("No answer");
}
return 0;
}