B. Kefa and Company

题目链接:http://codeforces.com/problemset/problem/580/B

题目大意: n个人,告诉你n个人的工资,但是请的客人的收入差值不能够超出给定的数字。每个人还有一个权值,现在从这n个人中选出m个人,使得他们的权值之和最大

思路:首先对每个人的工资进行排序,然后用尺取法找到一个符合条件的区间我们去计算这个区间内每个人的权值。然后找到最大的权值

AC代码:

 1 #include <cstdio>
 2 #include <string>
 3 #include <iostream>
 4 #include <algorithm>
 5 #include <cstdbool>
 6 #include <string.h>
 7 #include <math.h>
 8 
 9 using namespace std;
10 
11 typedef long long LL;
12 
13 typedef struct Node{
14     int value;
15     int friendship;
16 }Node;
17 
18 bool cmp (Node a,Node b)
19 {
20     return a.value < b.value;
21 }
22 
23 int main()
24 {
25     int n,d;
26     cin >> n >> d;
27     Node a[n];
28     for (int i=0;i<n;i++)
29     {
30         cin >> a[i].value >> a[i].friendship;
31     }
32     sort(a,a+n,cmp);
33     int l = 0,r = 0;
34     LL sum = 0,ans = 0;
35     while (l<n)
36     {
37         while (r < n && a[r].value - a[l].value < d)
38         {
39             sum += a[r].friendship;
40             r++;
41         }
42         ans = max(ans,sum);
43         sum -= a[l].friendship;
44         l++;
45     }
46     cout << ans << endl;
47     return 0;
48 }
原文地址:https://www.cnblogs.com/-Ackerman/p/11165897.html