ZOJ 3703 Happy Programming Contest(DP)

题目链接

输出路径,搞了一个DFS出来,主要是这里,浪费了好长时间。

 1 #include <cstdio>

 2 #include <string>

 3 #include <cstring>

 4 #include <iostream>

 5 #include <algorithm>

 6 using namespace std;

 7 int dp[51][1001];

 8 int c[51],v[51],que[51];

 9 int maxz,ti;

10 void dfs(int n,int T,int step)

11 {

12     int i,t1,t2;

13     if(n == 0)

14     {

15         if(maxz < step)

16         {

17             maxz = step;

18             sort(que,que+step);

19             t1 = t2 = 0;

20             for(i = 0;i < step;i ++)

21             {

22                 t1 += que[i];

23                 t2 += t1;

24             }

25             ti = t2;

26         }

27         else if(maxz == step)

28         {

29             sort(que,que+step);

30             t1 = t2 = 0;

31             for(i = 0;i < step;i ++)

32             {

33                 t1 += que[i];

34                 t2 += t1;

35             }

36             ti = min(t2,ti);

37         }

38         return ;

39     }

40     if(dp[n][T] == dp[n-1][T])

41     dfs(n-1,T,step);

42     if(T >= c[n]&&dp[n][T] == dp[n-1][T-c[n]] + v[n])

43     {

44         que[step] = c[n];

45         dfs(n-1,T-c[n],step+1);

46     }

47     return ;

48 }

49 int main()

50 {

51     int cas,T,n,i,j;

52     scanf("%d",&cas);

53     while(cas--)

54     {

55         memset(dp,0,sizeof(dp));

56         scanf("%d%d",&T,&n);

57         for(i = 1;i <= n;i ++)

58         scanf("%d",&c[i]);

59         for(i = 1;i <= n;i ++)

60         scanf("%d",&v[i]);

61         for(i = 1;i <= n;i ++)

62         {

63             for(j = 0;j <= T;j ++)

64             {

65                 if(j >= c[i])

66                 dp[i][j] = max(dp[i-1][j],dp[i-1][j-c[i]]+v[i]);

67                 else

68                 dp[i][j] = dp[i-1][j];

69             }

70         }

71         maxz = 0;

72         dfs(n,T,0);

73         printf("%d %d %d\n",dp[n][T],maxz,ti);

74     }

75     return 0;

76 }

 

你可能感兴趣的:(programming)