题目链接:https://vjudge.net/problem/CodeForces-1156B
题意:给定一串字符,相邻字符的ASCII码不能是相邻的数字,比如ABC,假设ASCII码为,99 100 101 ,
就是不符合题意的字符串,ACF,就可以。
思路:从相邻字符的ASCII码不能是相邻的数字,可以想到字符串之间ASCII码至少差2,然后发现
ACE...假设是奇数ASCII码,BDF是偶数ASCII码,那么我们不妨把他们分成两组,
奇数的字符,偶数的字符,那就简单了,我们可以直接先把奇数的输出,再把偶数的输出,那么字符串
之间相邻字符的ASCII码不能是相邻的数字就很好来解决了,下面字符串都转化为数字,列举一些情况
① 只有偶数
② 只有奇数
③ 1 3 5 7 2
④ 1 3 5 7 6
⑤ 1 3 2
⑥ 1 3 2 4
下面四种情况判定下就OK了,代码有呼应。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 #include <map> 7 #include <cmath> 8 #include <iomanip> 9 using namespace std; 10 11 typedef long long LL; 12 #define inf (1LL << 25) 13 #define rep(i,j,k) for(int i = (j); i <= (k); i++) 14 #define rep__(i,j,k) for(int i = (j); i < (k); i++) 15 #define per(i,j,k) for(int i = (j); i >= (k); i--) 16 #define per__(i,j,k) for(int i = (j); i > (k); i--) 17 18 19 int main(){ 20 21 ios::sync_with_stdio(false); 22 cin.tie(0); 23 24 char str[110]; 25 vector<int> one; 26 vector<int> two; 27 28 int T; 29 cin >> T; 30 while(T--){ 31 32 cin >> str; 33 34 one.clear(); //奇数 35 two.clear(); //偶数 36 int len = strlen(str) - 1; 37 rep(i,0,len){ 38 int tmp = str[i] - 'a' + 1; 39 //判奇偶 40 if(tmp & 1) one.push_back(tmp); 41 else two.push_back(tmp); 42 } 43 44 //排好序,方便比较 45 sort(one.begin(),one.end()); 46 sort(two.begin(),two.end()); 47 //只有偶数 48 if(one.size() == 0){ 49 rep(o,0,(int)two.size() - 1) cout << (char)('a' + two[o] - 1); 50 cout << endl; 51 } 52 //只有奇数 53 else if(two.size() == 0){ 54 rep(o,0,(int)one.size() - 1) cout << (char)('a' + one[o] - 1); 55 cout << endl; 56 } 57 else{ 58 int End_b = two.size() - 1; 59 int End_a = one.size() - 1; 60 61 //判断③④⑤⑥的情况 62 if(abs(two[0] - one[End_a]) != 1){ 63 rep(o,0,(int)one.size() - 1) cout << (char)('a' + one[o] - 1); 64 rep(o,0,(int)two.size() - 1) cout << (char)('a' + two[o] - 1); 65 cout << endl; 66 } 67 else if(abs(two[End_b] - one[0]) != 1){ 68 rep(o,0,(int)two.size() - 1) cout << (char)('a' + two[o] - 1); 69 rep(o,0,(int)one.size() - 1) cout << (char)('a' + one[o] - 1); 70 cout << endl; 71 } 72 else cout << "No answer" << endl; 73 74 } 75 76 } 77 78 getchar(); getchar(); 79 return 0; 80 }