K Best(最大化平均值)
Time Limit: 8000MS | Memory Limit: 65536K |
Total Submissions: 11555 | Accepted: 2978 |
Case Time Limit: 2000MS | Special Judge |
Description
Demy has n jewels. Each of her jewels has some value vi and weight wi.
Since her husband John got broke after recent financial crises, Demy has decided to sell some jewels. She has decided that she would keep k
.
Demy would like to select such k jewels that their specific value is maximal possible. Help her to do so.
Input
The first line of the input file contains n — the number of jewels Demy got, and k — the number of jewels she would like to keep (1 ≤ k ≤ n ≤ 100 000).
The following n lines contain two integer numbers each — vi and wi (0 ≤ vi ≤ 106, 1 ≤ wi ≤ 106, both the sum of all vi and the sum of all wi do not exceed 107
Output
Output k numbers — the numbers of jewels Demy must keep. If there are several solutions, output any one.
Sample Input
3 2 1 1 1 2 1 3
Sample Output
1 2
Source
題意:
就是最大化平均值。
POINT:
二分答案。
二分搜尋法模型:
條件C(x):可以挑選使得單位重量的物品價值不小於x->求滿足條件的最大x->如何判斷C(x)
價值和/重量和>=x
價值和-重量和*x>=0
和(價值-重量*x)>=0
可以對(價值-重量*x)的值進行貪心的選取,選取最大的k個 和>=0
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
using namespace std;
const int maxn = 100100;
typedef pair<double, int> pr;
int n,k;
int v[maxn];
int w[maxn];
int check(double x){
pr y[maxn];
for(int i=1;i<=n;i++){
y[i].first=v[i]-x*w[i];
y[i].second=i;
}
sort(y+1,y+1+n);
double sum=0;
for(int i=n;i>=n-k+1;i--){
sum+=y[i].first;
}
if(sum>0) return 1;
return 0;
}
void haha(double x){
pr y[maxn];
for(int i=1;i<=n;i++){
y[i].first=v[i]-x*w[i];
y[i].second=i;
}
sort(y+1,y+1+n);
for(int i=n;i>=n-k+1;i--){
if(i!=n) printf(" ");
printf("%d",y[i].second);
}
printf("\n");
}
void solve()
{
double l=0,r=100000;
while(fabs(l-r)>1e-6){
double mid=(l+r)/2;
if(check(mid)){
l=mid;
}else{
r=mid;
}
}
haha(l);
}
int main()
{
while(~scanf("%d %d",&n,&k)){
for(int i=1;i<=n;i++){
scanf("%d %d",&v[i],&w[i]);
}
solve();
}
}