# usaco2016open silver2 diamond

Diamond Collector(Silver)

Bessie想让这些陈列架上的钻石保持相似的大小，所以她不会把两个大小相差K以上的钻石同时放在一个陈列架上（如果两颗钻石的大小差值为K，那么它们可以同时放在一个陈列架上）。现在给出K，请你帮Bessie确定她最多一共可以放多少颗钻石在这两个陈列架上。

第一行输入两个值NK0<=K<1,000,000,000)

7 3

10

5

1

12

9

5

14

5

================================================================

#include <fstream>
#include <iostream>

using namespace std;

const int SIZE = 50005;

ifstream fin("diamond.in");
ofstream fout("diamond.out");

int N, K, diamond[SIZE];

int main() {
fin >> N >> K;
for (int i = 0; i != N; ++i) {
fin >> diamond[i];
}
sort(diamond, diamond + N);
/*fout << "The values of sorted Diamond[] are:" << endl;
for (int i = 0; i != N; ++i) {
fout << diamond[i] << " ";
}
fout << endl;*/
int j;
int leftMost[SIZE];
j = 0;
for (int i = 0; i != N; ++i) {
while (j != N && diamond[i] - diamond[j] > K) {
++j;
}
leftMost[i] = j;
}
/*fout << "The values of leftMost[] are:" << endl;
for (int i = 0; i != N; ++i) {
fout << leftMost[i] << " ";
}
fout << endl;*/
int leftMax[SIZE];
for (int i = 0; i != N; ++i) {
leftMax[i] = i - leftMost[i] + 1;
if (i > 0) {
leftMax[i] = max(leftMax[i], leftMax[i - 1]);
}
}
/*fout << "The values of leftMax[] are:" << endl;
for (int i = 0; i != N; ++i) {
fout << leftMax[i] << " ";
}
fout << endl;*/
int rightMost[SIZE];
j = N - 1;
for (int i = N - 1; i != -1; --i) {
while (j != -1 && diamond[j] - diamond[i] > K) {
--j;
}
rightMost[i] = j;
}
/*fout << "The values of rightMost[] are:" << endl;
for (int i = 0; i != N; ++i) {
fout << rightMost[i] << " ";
}
fout << endl;*/
int rightMax[SIZE];
for (int i = N - 1; i != -1; --i) {
rightMax[i] = rightMost[i] - i + 1;
if (i != N - 1) {
rightMax[i] = max(rightMax[i] , rightMax[i + 1]);
}
}
/*fout << "The values of rightMax[] are:" << endl;
for (int i = 0; i != N; ++i) {
fout << rightMax[i] << " ";
}
fout << endl;*/
int ans = 0;
for (int i = 0; i != N - 1; ++i) {
ans = max(ans, leftMax[i] + rightMax[i + 1]);
}
fout << ans << endl;
return 0;
}

• 写评论