1 条题解

  • 0
    @ 2021-6-14 23:29:51

    C :

    #include <stdio.h>
    int totalTime, medics;
    int value[100];
    int time[100];
    int max[1001];
    int main() 
    {
        scanf("%d%d", &totalTime, &medics);
        int i, t;
        for (i=0; i<medics; i++)
        {
            scanf("%d%d", &time[i], &value[i]);
        }
    
        for (i=0; i<medics; i++)
        {
            for (t=totalTime; t>0; t--)
            {
                if (time[i] <= t)
                {
                    if (value[i] + max[t-time[i]] > max[t])//第i个的价值+不选第i个且用时为t-time[i-1]时最大价值
                    {
                        max[t] = value[i] + max[t-time[i]];
                    }
                }
            }
        }
        printf("%d\n", max[totalTime]);
        return 0;
    }
    

    C++ :

    #include<iostream>
    #include<algorithm>
    using namespace std;
    int V[101][1001],w[101],v[101];
    int cnt,tim;
    int solve(int n)
    {
        for(int i=0;i<=n;i++)
            V[i][0]=0;
        for(int i=0;i<=n;i++)
            V[0][i]=0;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=tim;j++)
            if(j<w[i])
                V[i][j]=V[i-1][j];
            else
                V[i][j]=max(V[i-1][j],V[i-1][j-w[i]]+v[i]);
        return V[n][tim];
    }
    int main()
    {
        while(cin>>tim>>cnt)
        {
            for(int i=1;i<=cnt;i++)
                cin>>w[i]>>v[i];
            int ans=solve(cnt);
            cout<<ans<<endl;
        }
        return 0;
    }
    
    

    Pascal :

    var w,n,i,j:longint;p,a,v:array[0..1000]of longint; 
    begin
      read(w,n); 
      for i:=1 to n do read(a[i],v[i]); 
      for i:=1 to n do
        for j:=w downto a[i] do
          if p[j-a[i]]+v[i]>p[j] then p[j]:=p[j-a[i]]+v[i]; 
      i:=w; 
      writeln(p[w]); 
    end. 
    
    • 1