FJ is about to take his N (1 ≤ N ≤ 2,000) cows to the annual"Farmer of the Year" competition. In this contest every farmer arranges his cows in a line and herds them past the judges.
The contest organizers adopted a new registration scheme this year: simply register the initial letter of every cow in the order they will appear (i.e., If FJ takes Bessie, Sylvia, and Dora in that order he just registers BSD). After the registration phase ends, every group is judged in increasing lexicographic order according to the string of the initials of the cows’ names.
FJ is very busy this year and has to hurry back to his farm, so he wants to be judged as early as possible. He decides to rearrange his cows, who have already lined up, before registering them.
FJ marks a location for a new line of the competing cows. He then proceeds to marshal the cows from the old line to the new one by repeatedly sending either the first or last cow in the (remainder of the) original line to the end of the new line. When he’s finished, FJ takes his cows for registration in this new order.
Given the initial order of his cows, determine the least lexicographic string of initials he can make this way.
Input
- 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
Output
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.
Sample Input
6
A
C
D
B
C
B
Sample Output
ABCBCD
题意:
我也是看别人的博客才看懂的题意,复制如下;
思路:
最想象到的就是暴力,一个指针从头开始,一个从尾开始,逐渐移动;碰见不相同的就直接比较,碰见不相同的就用循环往里比较那个比较合适;(下一个字符小的比较合适);还有循环终止的条件,这是贪心暴力的策略;附上代码;
AC代码
#include <iostream>
#include<cmath>
#include<cstring>
using namespace std;
const int mod=1e9+7;
#define INF 0x3f3f3f3f
char s[2001];
char ss[2001];
int main()
{
int n;
cin >>n;
for(int i=0;i<n;i++)
cin >>s[i];
int str=0,end=n-1;
int ans=0;
int flag=0;
while(1)
{
if(str-end==1) break;
if(str==end)
{
ss[ans++]=s[str];
break;
}
if(s[str]>s[end])
{
ss[ans++]=s[end];
end--;
}
else if(s[str]<s[end])
{
ss[ans++]=s[str];
str++;
}
else
{
flag=0;
int x=str,y=end;
while(1)
{
x++;
y--;
if(x-y==1) break;
if(x==y) break;
if(s[x]>s[y])
{
flag=1;
ss[ans++]=s[end];
end--;
break;
}
else if(s[x]<s[y])
{
flag=1;
ss[ans++]=s[str];
str++;
break;
}
}
if(flag==0) ss[ans++]=s[str],str++;
}
}
for(int i=0;i<ans;i++)
{
if((i+1)%80==0&&(i+1)/80>0) cout <<ss[i]<<endl;
else cout <<ss[i];
}
return 0;
}
别的大佬的代码更简洁,cv如下:
#include<bits/stdc++.h>
using namespace std;
const int maxn=2000+5;
int n;
char c[maxn];
int main()
{
cin>>n;
for(int i=0;i<n;i++)
cin>>c[i];
int l=0,r=n-1;
while(l<=r)
{
bool left=false;
for(int i=0;i+l<r;i++)
{
if(c[l+i]<c[r-i])
{
left=true;
break;
}
else if(c[l+i]>c[r-i])
{
left=false;
break;
}
}
if(left)putchar(c[l++]);
else putchar(c[r--]);
}
cout<<endl;
}