CodeForces 580B(尺取法)

原文链接: http://www.cnblogs.com/sykline/p/9737776.html

Kefa and Company

题意:Kefa这个人要去吃饭,他要邀请一些朋友一起去,他的每个朋友有两个属性金钱和关系度,要求邀请的人里边任意两个人之间的金钱差的绝对值不大于d;求被邀请的所有朋友的关系度的和的最大值。

思路:将朋友按金钱从小到大排序,然后对关系度用尺取法求得最大值 ,这里要用前缀和来求区间内的关系度的和,不然会TLE。

代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#define FRE() freopen("in.txt","r",stdin)
#define INF 0x3f3f3f3f
#define inf 1000000000000

using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int maxn = 1e5+10;
struct Fi
{
    ll m,f;
}fp[maxn];
ll sum[maxn];
bool cmd(Fi &a,Fi &b)
{
    return a.m < b.m;
}

int main()
{
    ll n,d;
    memset(sum,0,sizeof(sum));
    scanf("%lld%lld",&n,&d);
    for(int i = 1; i <= n; i++)
        scanf("%lld%lld",&fp[i].m,&fp[i].f);

    sort(fp+1, fp+n+1, cmd);
    for(int i = 1; i <= n; i++)
        sum[i] = sum[i-1] + fp[i].f;

    int l = 1,r = 1;
    ll ans = -1;
    while(r <= n && l <= n)
    {
        if(fp[r].m - fp[l].m < d)
        {
            ans = max(ans, sum[r] - sum[l-1]);
            r++;
        }
        else
            l++;
    }
    printf("%lld\n",ans);
    return 0;
}
View Code

转载于:https://www.cnblogs.com/sykline/p/9737776.html

猜你喜欢

转载自blog.csdn.net/weixin_30701575/article/details/94789315