POJ 3111 K Best (01分数规划+二分)

K Best
Time Limit: 8000MS   Memory Limit: 65536K
Total Submissions: 6658   Accepted: 1756
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 = {i1i2, …, ik} as

POJ 3111 K Best (01分数规划+二分)_第1张图片.

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

题目大意不再说了,很简单。

01分数规划,和poj2976一样,具体的不多说。求sum(vi)/sum(wi)=x,转化得:sum(vi)-sum(wi)*x=0,所以二分x即可。

注意代码中的v和w不要单独定义 double v[maxn],w[maxn]
然后:
struct pp
{
	double c;
	int id;
}s[maxn];
这样去写会WA。

然后注意精度,50就可以,100会TLE。

/*
01分数规划+记录选择
*/
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define eps 1e-10

const int maxn=100000+10;
int k,n;

struct pp
{
	double c;
	int v,w;	//v,w一定要和id同在一个结构体里,不然会WA死
	int id;
}s[maxn];


int cmp(const pp &x,const pp &y){
	return x.c>y.c;
}

int cmp1(const pp &x,const pp &y){
	return x.id<y.id;
}

bool C(double x){
	int i;
	double sum=0;
	for(i=0;i<n;i++){
		s[i].c=s[i].v-s[i].w*x;
	}
	sort(s,s+n,cmp);
	for(i=0;i<k;i++)
		sum+=s[i].c;
	if(sum<0) return false;
	return true;
}

int main()
{
	int i;
	while(scanf("%d%d",&n,&k)!=EOF){
		for(i=0;i<n;i++){
			scanf("%d%d",&s[i].v,&s[i].w);
			s[i].id=i+1;
		}
		double l=0,r=10000000;
		for(i=0;i<50;i++){
			double m=(l+r)/2;
			if(C(m))
				l=m;
			else
				r=m;
		}
		sort(s,s+k,cmp1);
		for(i=0;i<k;i++)
			printf("%d%c",s[i].id,i==k-1?'\n':' ');
	}
	return 0;
}


你可能感兴趣的:(poj)