题目链接:http://codeforces.com/problemset/problem/580/B
某人有n个朋友,这n个朋友有钱数m和关系s两个属性。问如何选择朋友,使得这些朋友之间s最大差距小于d并且钱数是最多。
可以用滑动窗口,将m从小到大,s从大到小排列,这时在一个队列里维护队首和队尾,假如队首和队尾的s差距≥d时,就把队尾扔掉队首入队否则就仅队首入队。此时更新一下当前最大值。
1 #include <algorithm> 2 #include <iostream> 3 #include <iomanip> 4 #include <cstring> 5 #include <climits> 6 #include <complex> 7 #include <fstream> 8 #include <cassert> 9 #include <cstdio> 10 #include <bitset> 11 #include <vector> 12 #include <deque> 13 #include <queue> 14 #include <stack> 15 #include <ctime> 16 #include <set> 17 #include <map> 18 #include <cmath> 19 20 using namespace std; 21 22 typedef long long ll; 23 typedef struct Node { 24 int m; 25 int s; 26 }Node; 27 const int maxn = 100010; 28 int n, d; 29 Node f[maxn]; 30 31 bool cmp(Node a, Node b) { 32 if(a.m == b.m) return a.s > b.s; 33 return a.m < b.m; 34 } 35 36 int main() { 37 // freopen("in", "r", stdin); 38 while(~scanf("%d %d", &n, &d)) { 39 for(int i = 1; i <= n; i++) { 40 scanf("%d %d", &f[i].m, &f[i].s); 41 } 42 sort(f+1, f+n+1, cmp); 43 ll curans = 0; 44 ll ans = 0; 45 int front = 1; 46 int tail = 1; 47 while(1) { 48 if(front > n || tail > n) break; 49 if(f[tail].m - f[front].m >= d) 50 curans -= f[front++].s; 51 else curans += f[tail++].s; 52 ans = max(ans, curans); 53 } 54 printf("%I64d\n", ans); 55 } 56 return 0; 57 }
时间: 2024-11-03 20:55:01