给定长度为N(1≤N≤2000)的字符串S,要构造一个长度为N的字符串T。期初,T是一个空串,随后反复进行下列任意操作。
·从S的头部删除一个字符,加到T的尾部
·从S的尾部删除一个字符,加到T的尾部
目标是要构造字典序尽可能小的字符串
提示
Input
· Line 1: 一个整数(integer): N
· Lines 2~N +1: Line i+1 contains a single initial ('A'..'Z') of the string in the ith position in the original line
Output
输出时每行最多80个字符
Sample Input
6
A
C
D
B
C
B
Sample Output
ABCBCD
这道题目,虽然看着题意简单,我们可以这样想首尾比较将较小的字符装进空串中,但是有明显的BUG,比如CMABAC 这个你就要比较串内部的字符的大小了,不能单纯比较首尾的字符,还要比较内部的东西(还要简单的比较)。这时看了看大神思路,可以用string 来做,他可以简单比较整个字符串,而且也可以用反转函数来变一下字符串(用来拿首字符还是尾字符),总之思路简单,容易实现。
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<algorithm>
const int maxn=1000000;
typedef long long ll;
using namespace std;
int main()
{
char a;
int i,j;
string s; //原始字符串
string t; //空串
string t1; //反转串
int n;
cin>>n;
for(i=0;i<n;i++)
{
cin>>a;
s+=a;
}
t1=s;
while(s.length())
{
reverse(t1.begin(),t1.end());
if(t1<s)
{
t+=t1[0];
t1.erase(0,1);
s=t1;
}
else
{
t+=s[0];
s.erase(0,1);
t1=s;
}
}
for(i=0;i<t.length();i++)
{
cout<<t[i];
if((i+1)%80==0)
cout<<endl;
}
return 0;
}