Codeforces 1281B

Description

思路

题目大意是给定字符串s和c,要求交换s中至多两个字符,使得s字典序严格小于c。如果不存在输出“---”,否则输出交换后的s。

一开始总想着分类讨论。但是情况实在太多,写不过来。
后面看别人代码才知道应该先找到s交换两个字符后最小的字典序,然后再和c对比即可。

详见代码。

注意事项

第二个循环必须逆序循环以保证当有多个相等的数的情况下保证字典序最小。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define N 10000
#define inf 0x3f3f3f3f
 


int main() {
    ios::sync_with_stdio(false);
    int t;
    cin >> t;
    while(t--) {
        string s;
        string c;
        string tmp;
        cin >> s;
        cin >> c;
        tmp = s;
        sort(tmp.begin(), tmp.end());
        for(int i = 0; i < tmp.size(); i++) {
            if(tmp[i] != s[i]) {
                for(int j = tmp.size() - 1; j >= 0; j--) {
                    if(s[j] == tmp[i]) {
                        swap(s[i], s[j]);
                        goto done;
                    }
                }
            }
        }
        done:
        if(s < c) cout << s << endl;
        else cout << "---" << endl;
    }
}
原文地址:https://www.cnblogs.com/limil/p/12697053.html