[C++]Best Cow Line
Best Cow Line:
给定长度为N的字符串S,要构造一个长度为N的字符串T。起初,T是一个空串,随后反复进行下列任意操作。
- 从S的头部删除一个字符,加到T的尾部
- 从S的尾部删除一个字符,加到T的尾部
目标是要构造字典序尽可能小的字符串T
输入格式:
- Line 1: A single integer: N
- Lines 2…N+1: Line i+1 contains a single initial (‘A’…‘Z’) of the cow in the ith position in the original line
输出格式:
The least lexicographic string he can make. Every line (except perhaps the last one) contains the initials of 80 cows (‘A’…‘Z’) in the new line.
输入
6
A
C
D
B
C
B
输出
ABCBCD
解题思路:我们可以一直比较字符串S的‘头部’和‘尾部’,不断取较小的追加到T的尾部,如果S的头部和尾部相等,则逐步向里比较,直到得出结果。需要注意的是,输出结果每隔80个字符需要换行
#include<iostream>
#include<string>
using namespace std;
const int maxn = 10000;
int n;
char s[maxn];
int main(){
cin>>n;
for(int i = 0; i<n; i++){
cin>>s[i];
}
int i = 0, j = n-1;
int ans = 0;
while(i <= j){
int left = false;
int k = 0;
while(i+k <= j){
if(s[i+k] < s[j-k]){
left = true;
break;
}
if(s[i+k] > s[j-k]){
left = false;
break;
}
k++;
}
if(left){
cout<<s[i];
i++;
}
else {
cout<<s[j];
j--;
}
ans++;
if(ans == 80){
cout<<endl;
ans = 0;
}
}
}