Best Cow Line
题目大意 输入n个字符让你把按照顺序输入的字符字符串,重新组合成一个最小的字典序,规则是只能从给的字符串的开头和结尾取.然后80个字符后输出换行
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
代码实现
这道题是贪心算法核心就是比较字符串每个大小,然后关键就是相等的时候,需要继续比较。找到不相同的就跳出循环就行了
#include<iostream>
#include<cstdio>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int n;
char x[2005];
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>x[i];
}
int l=1;
int r=n;
int flag=0,cnt=0;
while(l<=r)
{
flag=0;
for(int i=0;l+i<=r;i++)
{
if(x[l+i]<x[r-i])
{
flag=1;
cnt++;
break;
}
else if(x[l+i]>x[r-i])
{
flag=0;
cnt++;
break;
}
}
if(flag) cout<<x[l++];
else cout<<x[r--];
if(cnt%80==0)
{
cnt=0;
cout<<endl;
}
}
cout<<endl;
}