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.
* 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
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.
6 A C D B C BSample Output
ABCBCD
题目大意:
给定一个初始字符串, 每次将这个字符串第一个和最后一个字符中较小的那一个构成新字符串的尾端, 重复这种操作直至构成一个同长度的新字符串。
解题思路:
对于新字符串来说, 有歧义的选择就只有首尾相等的情况。 如果后面存在不相等的两个对应的字符, 我们要先选择离字典序大的字符近的那一个。
举个例子:
BDACB 答案应该为 BBCAD
思路很简单, 不过这道题我PE了十几次。。。再一次感受到了好好读题的重要性。。。 每80个字符换一行!!! 下次要好好读题在写题了, 血的教训。。。
代码:
#include <sstream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iomanip>
#include <utility>
#include <string>
#include <cmath>
#include <vector>
#include <bitset>
#include <stack>
#include <queue>
#include <deque>
#include <map>
#include <set>
*ios::sync_with_stdio(false);
*freopen("input.txt", "r", stdin);
*/
typedef unsigned long long ull;
const int dir[9][2] = {0, 1, 0, -1, 1, 0, -1, 0, 1, 1, 1, -1, -1, 1, -1, -1, 0, 0};
const ll ll_inf = 0x7fffffff;
const int inf = 0x3f3f3f;
const int mod = 1000000;
const int Max = (int) 2e4 + 7;
char str[Max];
//freopen("input.txt", "r", stdin);
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf(" %c", &str[i]);
}
// check the answer
int i, j, cnt = 1;
for (int i = 0, j = n - 1; i <= j; ) {
bool l = 0;
for (int k = 0; i + k <= j; ++k) {
if (str[i + k] < str[j - k]) {
l = 1;
break;
} else if (str[i + k] > str[j - k]){
l = 0;
break;
}
}
if (l) printf("%c", str[i++]);
else printf("%c", str[j--]);
if ((cnt++) % 80 == 0) printf("\n");
}
//printf("%d\n", cnt);
return 0;
}