B. Mirror in the String
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You have a string s1s2…sns1s2…sn and you stand on the left of the string looking right. You want to choose an index kk (1≤k≤n1≤k≤n) and place a mirror after the kk-th letter, so that what you see is s1s2…sksksk−1…s1s1s2…sksksk−1…s1. What is the lexicographically smallest string you can see?
A string aa is lexicographically smaller than a string bb if and only if one of the following holds:
- aa is a prefix of bb, but a≠ba≠b;
- in the first position where aa and bb differ, the string aa has a letter that appears earlier in the alphabet than the corresponding letter in bb.
Input
The first line of input contains one integer tt (1≤t≤100001≤t≤10000): the number of test cases.
The next tt lines contain the description of the test cases, two lines per a test case.
In the first line you are given one integer nn (1≤n≤1051≤n≤105): the length of the string.
The second line contains the string ss consisting of nn lowercase English characters.
It is guaranteed that the sum of nn over all test cases does not exceed 105105.
Output
For each test case print the lexicographically smallest string you can see.
Example
input
Copy
4 10 codeforces 9 cbacbacba 3 aaa 4 bbaa
output
Copy
cc cbaabc aa bb
Note
In the first test case choose k=1k=1 to obtain "cc".
In the second test case choose k=3k=3 to obtain "cbaabc".
In the third test case choose k=1k=1 to obtain "aa".
In the fourth test case choose k=1k=1 to obtain "bb".
---------------------------------------------------------------------------------------------------------------------------------
观察样例本来是可以推出严格单调的一段是答案,但是对于baa
来说
bb
baab
baaaab
第三个显然小于第二个
多写几组
cbbaa
cc
cbbc
cbbbbc
cbbaabbc也就是非严格递减满足条件
但又和样例发生矛盾
bbaa这也是非严格递减
bb
bbaa可以看出只要前两个字母相同,加上第二个一定会扩大答案,然而第一个字母和第二个字母不同,后面非严格递减时,取的越长越好,why?因为回文的话,后半段必定是有增加的趋势的,我们把大的不停往后推,它的地位就不停降低了。
# include <stdio.h>
#include<iostream>
# include<cstring>
# include<vector>
# include<algorithm>
using namespace std;
typedef long long int ll;
int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
string s;
cin>>s;
if(s[0]==s[1])
{
cout<<s[0]<<s[1]<<'\n';
}
else
{
char now=s[0];
s[n]='z'+1;
for(int i=0; i<=n; i++)
{
if(now>=s[i])
{
now=s[i];
}
else
{
for(int j=0; j<=i-1; j++)
{
cout<<s[j];
}
for(int j=i-1; j>=0; j--)
{
cout<<s[j];
}
cout<<'\n';
break;
}
}
}
}
return 0;
}