贪心好题——USACO 2005 October Silver Allowance

http://poj.org/problem?id=3040

注意到这么一句话where each denomination of coin evenly divides the next-larger denomination

想到贪心,排个序,从高往下取

同时加个最小公倍数的优化时间0ms

贪心好题——USACO 2005 October Silver Allowance View Code
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;

int hash1[21];

struct data
{
int v,b;
}s[29];

int cmp(data a,data b)
{
return a.v<b.v;
}

int main()
{
int n,c;
while(scanf("%d%d",&n,&c)!=EOF)
{
int i,j;
for(i=1;i<=n;i++)
{
scanf("%d%d",&s[i].v,&s[i].b);
}
sort(&s[1],&s[n+1],cmp);

int ok=1,add=0,temp,left;
while(ok)
{
left=c;
for(i=1;i<=n;i++)hash1[i]=0;

for(i=n;i>=1;i--)
{
if(s[i].b==0)continue;

temp=min(left/s[i].v,s[i].b);
left=left-temp*s[i].v;
//s[i].b-=temp;
hash1[i]=temp;
}

if(left!=0)
for(i=1;i<=n;i++)
{
if(left<=0)break;
if(s[i].b-hash1[i]==0)continue;
//s[i].b--;
left-=s[i].v;
hash1[i]++;
}

if(left<=0)
{
int mmin=9999999;
for(j=1;j<=n;j++)
{
if(hash1[j]==0)continue;
mmin=min(s[j].b/hash1[j],mmin);
}
for(j=1;j<=n;j++)
{
if(hash1[j]==0)continue;
s[j].b-=mmin*hash1[j];
}
add+=mmin;
//left=c;
}
else
ok=0;
}

printf("%d\n",add);

}
}



你可能感兴趣的:(USACO)