【POJ-3617】Best Cow Line

97 阅读1分钟
题意

给定长度为N的字符串S,要构造一个长度为N的字符串T。起初,T是一个空串,随后反复进行下列任意操作。

​ 从S的头部删除一个字符,加到T的尾部

​ 从S的尾部删除一个字符,加到T的尾部

目标是构造字典序尽可能小的字符串。

 

 

样例
Sample Input
6
A
C
D
B
C
B

Sample Output
ABCBCD

 



 

AC代码
#include <iostream>
#include<algorithm>
using namespace std;

int fun(char c[],int i,int j)
{
    if(abs(i-j)>=2)   //为了防止溢出,在i和j快要碰到的时候马上停住
    {
        int ii=i+1,jj=j-1;  //探针
        if(c[ii]<c[jj])
        {
            return 1;
        }
        else if(c[ii]>c[jj])
        {
            return 2;
        }
        else   //下一位仍相等,则递归判断下下一位。。。
        {
            return fun(c,ii,jj);   //如果直接第调用函数“fun(c,ii,jj)”而没有在前面加上“return”,就会报“wrong answer”,加上return后,只报“Presentation Error”
        }
    }
    return -1;

}
int main()
{
    int n;
    int ans=0;
    char c[2001];
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>c[i];
    }
    int i=1,j=n;
    while(i<=j)
    {
        if(c[i]<c[j])
        {
            //cout<<c[i]<<i<<endl;
            cout<<c[i];
            i++;
        }
        else if(c[i]>c[j])
        {
            //cout<<c[j]<<j<<endl;
            cout<<c[j];
            j--;
        }
        else //相等的情况,判断下一位
        {
            if(fun(c,i,j)==1)
            {
                //cout<<c[i]<<i<<endl;
                 cout<<c[i];
                 i++;
            }
            else if(fun(c,i,j)==2)
            {
                //cout<<c[j]<<j<<endl;
                cout<<c[j];
                j--;
            }
            else
            {
                //cout<<c[i]<<i<<endl;
                 cout<<c[i];
                 i++;
            }
        }
        ans++;
        if(ans%80==0)    //如果没有这一句,就一直报“Presentation Error”。至于为什么要“ans%80==0”,不是很清楚。
            cout<<endl;
    }
    cout<<endl;
    return 0;

}


 

题源:poj.org/problem?id=…