poj 3111 二分水题

题意:有n个物品的重量和价值分别是w[i]和v[i],从中选出K个物品使得单位重量的价值最大


贪心的反例是显然的,nyoj的样例就是

本题是个二分的很好例子,可以理解成二分得到一个阈值,然后判断是否够k个,以此得到最优解,而这个正确性也是显然的


#include   
#include   
#include   
#include   
#define rep(i, j, k) for(int i = j; i <= k; i++)

using namespace std;  

const int INF=0x3f3f3f3f;  
int n,k;  

struct cadongllas
{  
    double v,w,tmp;  
    int id;  
}s[100005];  

bool cmp(cadongllas x,cadongllas y)
{
    return x.tmp>y.tmp;  
}  


bool judge(double d)
{  
    double sum = 0;
	rep (i, 1, n)
    	s[i].tmp=s[i].v-d*s[i].w;  
	sort (s + 1, s + 1 + n, cmp);
	rep (i, 1, k)
    	sum+=s[i].tmp;  
    return sum>=0;  
} 

int main()
{  
    while(scanf("%d%d",&n,&k)!=EOF){  
		rep (i, 1, n)
			scanf ("%lf%lf", &s[i].v, &s[i].w), s[i].id = i;
        double l = 0, r = 0x7fffffff * 1.0;
		rep (i, 0, 101)
		{  
            double mid=(l+r)/2;  
            if(judge(mid))  
            	l=mid;  
            else  
            	r=mid;  
        }  
		rep (i, 1, k)
        	printf("%d ",s[i].id);  
        printf("\n");  
    }  
    return 0;  
}


你可能感兴趣的:(POJ,二分)