|
饭卡 Time Limit: 5000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Problem Description 电子科大本部食堂的饭卡有一种很诡异的设计,即在购买之前判断余额。如果购买一个商品之前,卡上的剩余金额大于或等于5元,就一定可以购买成功(即使购买后卡上余额为负),否则无法购买(即使金额足够)。所以大家都希望尽量使卡上的余额最少。
Input 多组数据。对于每组数据:
Output 对于每组输入,输出一行,包含一个整数,表示卡上可能的最小余额。
Sample Input 1 50 5 10 1 2 3 2 1 1 2 3 2 1 50 0
Sample Output -45 32
|
#include<stdio.h>
#include<string.h>
int max(int a,int b)
{
return a>b? a:b;
}
int main()
{
int n,m;
while(scanf("%d",&n)!=EOF&&n!=0)
{
int i,k,temp,max1,j;
int price[1005]={0};
int dp[1005]={0};
for(i=1;i<=n;i++)
{
scanf("%d",&price[i]);
}
for(i=0;i<n;i++)
{
for(k=1;k<n;k++)
{
if(price[k]>price[k+1])
{
temp=price[k];
price[k]=price[k+1];
price[k+1]=temp;
}
}
}
max1=price[n];
scanf("%d",&m);
if(m<5)
{
printf("%d\n",m);
continue ;
}
else
m=m-5;
for(i=1;i<n;i++)
for(j=m;j>=price[i];j--)
{
dp[j]=max(dp[j],dp[j-price[i]]+price[i]);
}
printf("%d\n",m+5-max1-dp[m]);
}
return 0;
}
c++代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
int cmp(int a1,int b1)
{
return a1<b1;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n!=0)
{
int m,i,j,max1;
int price[1005]= {0},dp[1005]= {0};
for(i=1; i<=n; i++)
scanf("%d",&price[i]);
sort(price+1,price+1+n,cmp);
max1=price[n];
scanf("%d",&m);
if(m<5)
{
printf("%d\n",m);
continue;
}
m-=5;
for(i=0; i<n; i++)
for(j=m; j>=price[i]; j--)
{
dp[j]=max(dp[j],dp[j-price[i]]+price[i]);
}
printf("%d\n",m+5-max1-dp[m]);
}
return 0;
}