P3143 [USACO16OPEN]钻石收藏家Diamond Collector

题目描述
Bessie the cow, always a fan of shiny objects, has taken up a hobby of mining diamonds in her spare time! She has collected diamonds () of varying sizes, and she wants to arrange some of them in a pair of display cases in the barn.
Since Bessie wants the diamonds in each of the two cases to be relatively similar in size, she decides that she will not include two diamonds in the same case if their sizes differ by more than (two diamonds can be displayed together in the same case if their sizes differ by exactly ). Given , please help Bessie determine the maximum number of diamonds she can display in both cases together.
奶牛Bessie很喜欢闪亮亮的东西(Baling~Baling~),所以她喜欢在她的空余时间开采钻石!她现在已经收集了N颗不同大小的钻石(N<=50,000),现在她想在谷仓的两个陈列架上摆放一些钻石。
Bessie想让这些陈列架上的钻石保持相似的大小,所以她不会把两个大小相差K以上的钻石同时放在一个陈列架上(如果两颗钻石的大小差值为K,那么它们可以同时放在一个陈列架上)。现在给出K,请你帮Bessie确定她最多一共可以放多少颗钻石在这两个陈列架上。
输入输出格式
输入格式:

The first line of the input file contains and ().
The next lines each contain an integer giving the size of one of the
diamonds. All sizes will be positive and will not exceed .

输出格式:

Output a single positive integer, telling the maximum number of diamonds that
Bessie can showcase in total in both the cases.

输入输出样例
输入样例#1:
7 3
10
5
1
12
9
5
14
输出样例#1:
5


动态规划:
设f[i]表示以i为开头的最大延伸长度,g[i]表示以i为结尾的最大延伸长度。
答案就是max{f[i+1]+g[i]}。
求f,g时不能直接暴力,需要优化。


#include
#include
#include
using namespace std;
int n,k,ans,pos,cnt,a[50005],f[50005],g[50005];
int main()
{
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++)
        scanf("%d",a+i);
    sort(a+1,a+n+1);
    cnt=0,pos=n;
    for(int i=n;i>=1;i--)
    {  
        cnt++;
        int tmp=pos;
        for(int j=tmp;j>=1;j--)
        {
            tmp--;
            if(a[j]-a[i]<=k)
                break;
            else
                cnt--;
        }
        pos=tmp+1;
        f[i]=max(f[i+1],cnt);
    }
    cnt=0,pos=1;
    for(int i=1;i<=n;i++)
    {
        cnt++;
        int tmp=pos;
        for(int j=tmp;j<=n;j++)
        {
            tmp++;
            if(a[i]-a[j]<=k)
                break;
            else
                cnt--;
        }
        pos=tmp-1;
        g[i]=max(cnt,g[i-1]);
    }
    for(int i=1;i<=n;i++)
        ans=max(ans,f[i+1]+g[i]);
    printf("%d\n",ans);
    return 0;
}

你可能感兴趣的:(动态规划)