POJ 3167 字典序最小问题

4 篇文章 0 订阅

题目连接

http://poj.org/problem?id=3617

Description

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

题意

贪心选择构造最小的字典序字符串
有两个选择,把头部删除假如到构造串的尾部,或者把尾部删除加入构造串的尾部,使构造的串的字典序最小。

题解

前后比较,输出较小的。
需要注意,假如相等的时候,需要跳过这两个数,比较下一组数(也可能还需要比较下下组数),然后根据比较的结果选择输出相等的哪一边的数。

代码

#include<iostream>
  #include<cstdio>
  #include<cstring>
  #include<string>
  #include<cmath>
  #include<string>
 #include<cctype>
  #include<algorithm>
  #include<vector>
#define INF  1e9+7
using namespace std;
char a[2010];
int main(int argc, char const *argv[])
{
    int n;
    while(scanf("%d",&n)!=EOF){

    for (int i = 0; i < n; ++i)
    {
        cin>>a[i]; 
    }
    int p=0,q=n-1;
    int cnt=0;
    while(p<=q){
        bool ok=false;
    for (int i = 0; p+i < q-i; ++i)
    {
        if (a[p+i]<a[q-i])
        {
            ok=true;
            break;
        }
        else if(a[p+i]>a[q-i]){
            break;
        }
    }
    if(ok){
        printf("%c",a[p++]);
        cnt++;
    }
    else{
        printf("%c",a[q--]);
        cnt++;
    }
    if(cnt%80==0){
        putchar('\n');
    }
}
putchar('\n');}
    return 0;
}

Ps

特别坑的,输出的时候每一排只有80个字符,每80个还要跳行输出…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值