题目描述
题目描述
FJ is about to take his N (1 ≤ N ≤ 500,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.
算法1
简单的说就是从输入字符串队首队尾抽取字符串组成输出 要求输出字符串字典序最小
算法1
我们来贪心选取 队首队尾哪个字典序小 就选择哪个。
关键在队首队尾相同那么就看次一级的字母的字典序 但是要考虑诸如 aca vav aa 等边界情况。
需要处理好
吐槽下 POJ 的提交和没有错误提示。
#include <iostream>
#include <queue>
#include <string>
using namespace std;
char input[500010];
char output[500010];
int idx;
int SelectCopy(int l, int r)
{
if (l >= r) return 1;
if (input[l] < input[r]) {
return -1;
}
else if (input[l] > input[r]) {
return 1;
}
else {
int copyl = l + 1; int copyr = r - 1;
return SelectCopy(copyl, copyr);
}
return 0;
}
void Select(int l, int r)
{
if (l == r) { output[idx] = input[l]; idx++; return; }
if (l > r) return;
if (input[l] < input[r]) {
output[idx] = input[l];
idx++; l++;
}
else if (input[l] > input[r]) {
output[idx] = input[r];
idx++; r--;
}
else {
//相等
int copyl = l + 1; int copyr = r - 1;
int selectidx = SelectCopy(copyl, copyr);
if (-1 == selectidx) {
output[idx] = input[l];
idx++; l++;
}
else if (1 == selectidx) {
output[idx] = input[r];
idx++; r--;
}
}
if (l <= r) {
Select(l, r);
}
}
int main()
{
int N;
cin >> N;
for (int i = 0; i < N; i++) {
char t;
cin >> t;
input[i] = t;
}
int l = 0; int r = N - 1;
Select(l, r);
for (int i = 0; i < idx; i++) {
if (i % 80 == 0 && i>=80) cout << endl;
cout << output[i];
}
return 0;
}
PE了无数次。。。 难受
其实 作假设然后验证 定位BUG的位置 才是最后自己学习到的真正财富。我觉得比学会一个模板 知道一个高级结构的使用还受益更多。
您收获打了,hh
同意,是得耐下心捋清楚思路才行呢~hh