Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

用背包算法为什么会超时????高手赐教,谢谢!!

Posted by nmb at 2005-08-19 01:26:38 on Problem 2581
我的程序如下:
#include<stdio.h>
int num[4],m[5];
int Knap(int s,int n,int w[])
{
    int i;
    if(s==0)return 1;
    if(s<0||n<1)return 0;

    if(Knap(s-w[n-1],n-1,w)==1)
    {
        for(i=0;i<4;i++)if(w[n-1]==m[i+1]){num[i]++;break;}
        return 1;
        }
    return Knap(s,n-1,w);
}

main()
{
    int money[4];
    int i,j,k,s,my,t;
    float s2,s1;
    int w[402];
    m[1]=25;
    m[2]=10;
    m[3]=5;
    m[4]=1;
    while(scanf("%f%d%d%d%d",&s2,&money[0],&money[1],&money[2],&money[3])!=EOF){
        k=0;

        s=(int)(s2*100)+1;
        s1=s/100.0;
        if(s1>s2)
        s--;
        for(i=0;i<4;i++)k+=money[i];
        my=k-1;
        for(i=0;i<4;i++){
             num[i]=0;
             for(j=0;j<money[i];j++){
                 w[my--]=m[i+1];
                 }
            }
        if(Knap(s,k,w)==1)
            for(i=0;i<4;i++)
            {
                if(i!=3)printf("%d ",num[i]);
                else printf("%d\n",num[i]);
            }
        else printf("NO EXACT CHANGE\n");
        }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator