Valera has only one electrical socket in his flat. He also has m devices which require electricity to work. He's got n plug multipliers to plug the devices, the i-th plug multiplier has ai sockets.
A device or plug multiplier is supplied with electricity if it is either plugged into the electrical socket, or if it is plugged into some plug multiplier which is supplied with electricity.
For each device j, Valera knows the safety value bj which is the maximum number of plug multipliers on the path between the device and the electrical socket in his flat. For example, if bj = 0, the device should be directly plugged into the socket in his flat.
What is the maximum number of devices Valera could supply with electricity simultaneously? Note that all devices and plug multipliers take one socket to plug, and that he can use each socket to plug either one device or one plug multiplier.
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 2·105), the number of plug multipliers and the number of devices correspondingly.
The second line contains n space-separated integers a1, a2, ..., an (2 ≤ ai ≤ 2·105). Here, the number ai stands for the number of sockets on the i-th plug multiplier.
The third line contains m space-separated integers b1, b2, ..., bm (0 ≤ bj ≤ 2·105). Here, the number bj stands for the safety value of the j-th device.
Print a single integer: the maximum number of devices that could be supplied with electricity simultaneously.
3 5 3 2 2 1 2 2 1 1
4
3 3 2 2 2 1 2 2
3 题意:给n个设备和m个排插,开始有一个插口,每个排插有ai个插孔,每个设备有一个安全值,表示它最多接到第bi层过度排插上,问最多能插多少电器。 分析:将b值从大到小排序后,最优方案一定可以表示成一段b的前缀,于是我们可以二分这个前缀的长度来贪心地验证,优先放b值小的,优先接a值大的插板。#include<iostream> #include<string> #include<algorithm> #include<cstdlib> #include<cstdio> #include<set> #include<map> #include<vector> #include<cstring> #include<stack> #include<cmath> #include<queue> #include <unordered_map> #define INF 0x3f3f3f3f #define eps 1e-9 #define MOD 1000000007 using namespace std; int n,m,a[200005],b[200005]; bool check(int mid) { if(mid == 1) return true; if(b[mid] == 0) return false; int res = a[1],nowdep = 1,now = mid,nowi = 1; while(true) { while(b[now] == nowdep && now && res) { res--; now--; } if(now && !res) return false; if(!now) return true; int tot = 0; while(res) { if(nowi == n) break; tot += a[++nowi]; res--; } nowdep++; res += tot; } } bool camp(int x,int y) { return x > y; } int main() { scanf("%d%d",&n,&m); for(int i = 1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1;i <= m;i++) scanf("%d",&b[i]); sort(a+1,a+1+n,camp); sort(b+1,b+1+m,camp); int l = 0,r = m; while(l != r) { int mid = (l+r)/2 + 1; if(check(mid)) l = mid; else r = mid-1; } cout<<l<<endl; }