Diamond Collector

问题描述

USACO 2016 US Open Contest, Bronze Problem 1. Diamond Collector https://usaco.org/index.php?page=viewproblem2&cpid=639

给定长度为 NN 的数组和 KK ,输出 subsequencesubsequence 最长的长度,要求 subsequencesubsequence 中任意两数之差不超过 KK

样例

input :

5 3
1
6
4
3
1

output :

4

思路

遍历数组中每个数 xx ,遍历搜索数组中有几个 yy 使得 yy 大于 xxyx<=Ky - x <= Kansans 更新为最长的长度。

yyxx 之差不能使用 absabs 绝对值。因为这样会导致一个 yyxxKK ,另一个 yyxxKK,那么这两个 yy 的差值大于 KK,导致答案错误。 # 代码

#include <bits/stdc++.h>
using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    freopen("diamond.in", "r", stdin);
    freopen("diamond.out", "w", stdout);
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for(int& x:a) cin >> x;
    int ans = 0;
    for(int x: a){
        int now = 0;
        for(int y:a){
            if(y >= x && y - x <= k) now++;
        }
        ans = max(ans, now);
    }
    cout << ans;
    return 0;
}

Diamond Collector
https://mingsm17518.github.io/2026/04/30/算法学习/03_Bronze/01_Complete_Search/02_Diamond_Collector/
作者
Ming
发布于
2026年4月30日
更新于
2026年9月13日
许可协议