K Best(二分与思考)
K Best
Time Limit: 8000MS |
|
Memory Limit: 65536K |
Total Submissions: 7491 |
|
Accepted: 1936 |
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 best jewels for herself. She decided to keep such jewels that their specific value is as large as possible. That is, denote the specific value of some set of jewels S = {i1, i2, …, ik} as
.
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
在最终只能留下k个首饰的前提下,问最大的s=(v1+v2+....vk)/(w1+w2+...wk)
对s的值进行二分,对于每个确定的s有每个珍宝都有确定的v[i]-s*w[i]令为u,让最大的k个u相加,如大于0则可行
这里有一个问题:为什么不能直接对每个珠宝算价格除重量然后取出最大的k个?
答:
可能是这样的:两种珠宝虽然价重比可能相同,但是其中一种可能价格和重量都十分之大,所以在分式中的影响也很大,甚至能够抵消它本身价重比的劣势。可以尝试1/4分别加上50/100和2/3
代码:
#include<algorithm>
#include<iostream>
#include<cstring>
#include<string>
#include<cstdio>
#include<vector>
#include<stack>
#include<cmath>
#include<queue>
#include<set>
#include<map>
#define md(x,y) (x+y)/2
const int maxn=1000100;
using namespace std;
const int size=1e6+5;
struct node{
double val;
int no;
};
double v[size],w[size];
node r[size];
int n,k;
bool cmp(node a,node b)
{
return a.val>b.val;
}
int check(double x)
{
int i;
for(i=0;i<n;i++)
{
r[i].val=v[i]-x*w[i];
r[i].no=i+1;
}
sort(r,r+n,cmp);
double sum=0;
for(i=0;i<k;i++)
{
sum+=r[i].val;
}
return sum>=0;
}
int main()
{
while(cin>>n>>k)
{
int i;
for(i=0;i<n;i++)
{
scanf("%lf%lf",&v[i],&w[i]);
r[i].val=v[i]/w[i];
r[i].no=i+1;
}
double rite=maxn,l=0;
while(rite-l>1e-7)
{
double mid=md(l,rite);
if(check(mid))
{
l=mid;
}
else rite=mid;
}
for(int i=0;i<k;i++)
{
printf("%d",r[i].no);
if(i!=k-1) printf(" ");
else printf("\n");
}
}
return 0;
}
时间卡得紧,用scanf,printf