您的位置:首页 > 其它

Gym - 101102F F. Exchange 贪心、简单题

2017-01-14 21:36 309 查看
F. Exchange

time limit per test
0.5 seconds

memory limit per test
256 megabytes

input
standard input

output
standard output

Given a string of lowercase English letters. You are allowed to choose two letters that exist in any position in the string, replace all occurrences of the first letter you chose with the second one, and replace all occurrences of the second letter you chose
with the first one.

Your task is to find the string that comes first in dictionary order among all possible strings that you can get by performing the above operation at most once.

For example, by exchanging letter ‘a’ with letter ‘h’ in string “hamza”, we can get string “ahmzh”.

Input

The first line of input contains a single integer T, the number of test cases.

Each test case contains a non-empty string on a single line that contains no more than 105 lowercase
English letters.

Output

For each test case, print the required string on a single line.

Example

input
3
hamza
racecar
mca


output
ahmzh
arcecra
acm


Source

2016 ACM Amman Collegiate Programming Contest

UESTC 2017 Winter Training #1

Gym - 101102F

My Solution

题意:可以对字符串进行一个操作,把2个字母互换(这2个字母是不同的),一旦互换必须把所有x换成y,所有y换成x,最多可以进行一次这样的操作,求字典序最小的字符串。

 贪心、简单题

用cnt[i]表示字母出现的次数,用flag[i]表示之前j字母是否出现过,

对于每个字母x,则在1~x-1里找之前没有出现过但在整个字符串出现过的字母进行互换,找出后退出循环,之后进行互换

复杂度 O(26*n)

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 8;

string s;
int cnt[26];//, cur[maxn][6];
bool flag[26];
int main()
{
#ifdef LOCAL
freopen("e.txt", "r", stdin);
//freopen("e.out", "w", stdout);

#endif // LOCAL
ios::sync_with_stdio(false); cin.tie(0);
int T, sz, a, b, i, j;
cin >> T;
while(T--){
memset(cnt, 0, sizeof cnt);
//memset(cur, 0, sizeof cur);
memset(flag, false, sizeof flag);
a = b = -1;
cin >> s;
sz = s.size();
for(i = 0; i < sz; i++){
cnt[s[i] - 'a']++;
}

for(i = 0; i < sz; i++){
flag[s[i] - 'a'] = true;
if(a != -1) break;
if(s[i] - 'a' == 0) continue;
else{
for(j = 0; j < s[i] - 'a'; j++){
if(cnt[j] != 0 && !flag[j]){
a = s[i] - 'a', b = j;
break;
}
}
}

}
if(a == -1) cout << s << endl;
else{
for(i = 0; i < sz; i++){
if(s[i] - 'a' == a){
s[i] = 'a' + b;
}
else if(s[i] - 'a' == b){
s[i] = 'a' + a;
}
}
cout << s << endl;
}
}
return 0;
}



  Thank you!

                                                                                                           
                                   ------from ProLights
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: