Codeforces Round #607 (Div. 2)
https://codeforces.com/problemset/problem/1281/B
题意:每个测试用例给定两个字符串chr1,chr2,若按字典序排序前者小于后者则直接输出chr1,否则对chr1字符数组最多交换一对字符,若可以满足chr1<chr2则输出交换后的chr1,若无论怎么交换都不能满足则输出“---”;
题解:采用贪心思想,用下标i从前往后遍历chr1,将当前i所指向的字符设为min,即char min=chr1[i]; 同时再设一个下标sign从后往前遍历,sign--;若chr1[sign]<min,则min=chr1[sign],同时标记sign;当sign<=i时结束sign的此次查找,判断若sign发生改变则break退出i的遍历,否则continue;因为题目要求至多一次交换。break后交换两字符,若strcmp(chr1,chr2)<0则输出chr1,否则输出“---”。
#include <iostream> #include <cmath> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include <vector> #include <map> using namespace std; char chr1[5005],chr2[5005]; int main() { int t; cin>>t; while(t--) { scanf("%s %s",chr1,chr2); if(strcmp(chr1,chr2)<0) cout<<chr1<<endl; else{ int sign_first=0,sign_last=0; int len1=strlen(chr1); for(int i=0;i<len1;i++) { char chr=chr1[i]; int sign=len1-1; sign_last=i; while(sign>i) { if(chr1[sign]<chr){ chr=chr1[sign]; sign_last=sign; } --sign; } sign_first=i; if(sign_last==i) continue; else break; } swap(chr1[sign_last],chr1[sign_first]); if(strcmp(chr1,chr2)<0) printf("%s ",chr1); else cout<<"--- "; } } return 0; }