您的位置:首页 > 大数据 > 人工智能

51Nod 1335 思维

2017-08-27 19:34 453 查看
题目链接

思路:

根据题意,要求最终字符串的字典序最小,则要求原字符串的小字符尽量换到前面,大的字符换到后面。

考虑将字符串从小到大排序,则与原字符一一比较后的第一个不同的字符一定是交换的起点,假设其在原串的位置为pos。

然后考虑枚举交换的终点,因为原字符串的终点字符一定是排序后新串的第pos个位置的字符。

若存在多个,则模拟翻转,与答案比较并更新。

总复杂度:O(Tn2)

代码:

#include<cmath>
#include<string>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
string s,ne,ans,tem;
int main(){
ios::sync_with_stdio(false);
int T;cin >> T;
while(T--){
cin >> s;ne = s;
sort(ne.begin(),ne.end());
int len = s.length();

int pos = len;
for(int i=0 ;i<len ;i++){
if(s[i] > ne[i]){
pos = i;
break;
}
}
if(pos == len) cout << 0 << " " << 0 << endl;
else{
ans = s;
int st = pos,ed = st;
for(int i=pos+1 ;i<len ;i++){
if(s[i] != ne[pos]) continue;
tem = s;
reverse(tem.begin()+pos,tem.begin()+i+1);
if(tem < ans){ans = tem;ed = i;}
}
cout << st << " " << ed << endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息