The main topic: There are n songs, M discs, each disc can put a T-time song, give the length of each song, you must sequentially input the disc (you can choose not to record a few songs), the maximum number of songs can be recorded.
Use D[i][j][0] to express the first song, put J first, at least how many discs, with d[i][j][1] to represent the first song, put J first, the minimum CD, the last disc can be the maximum capacity remaining. Complete the recursion according to whether I put the first song.
This recursion is correct, because the first song, put J first case, the best case is to use as few discs as possible, and make the last disc capacity as large as possible (for example, if the number of discs used more, and the last disc more capacity, this situation is not as good as before). A scrolling array is used in the program to optimize memory.
State transition equation:
If D[i-1][j][1]>=a[i], if put I, the number of discs unchanged, the remaining capacity is less,
If D[i-1][j][1]<a[i], then if I, the number of discs plus 1, the remaining capacity of v-a[i].
#include <stdio.h> #include <stdlib.h> #include <string.h>int a[1530];int D[2][1530][2];char e[ 100010];int Main (void) {int i,j,v,n,m,pi,qi,p1,p2,minp1,minp2,sump,top,lo,cur,ans;scanf ("%d", &pi); for (Qi=1;qi <=pi;qi++) {scanf ("%d%d%d", &n,&v,&m), while (getchar () = = ') {;} Gets (e+1); Lo=strlen (e+1); Top=0;i=1;while (I<=lo) {if (e[i]>= ' 0 ') && (e[i]<= ' 9 ')) {Sump=0;while (e[ i]>= ' 0 ') && (e[i]<= ' 9 ')) {sump=sump*10+e[i]-' 0 '; i++;} Top++;a[top]=sump;} else{i++;}} Cur=1;for (i=1;i<=n;i++) {cur^=1;if (D[cur^1][i-1][1]>=a[i]) {d[cur][i][0]=d[cur^1][i-1][0];d [cur][i][1]=d[ Cur^1][i-1][1]-a[i];} Else{d[cur][i][0]=d[cur^1][i-1][0]+1;d[cur][i][1]=v-a[i];} for (j=1;j<i;j++) {minp1=d[cur^1][j][0];minp2=d[cur^1][j][1];if (D[cur^1][j-1][1]>=a[i]) {p1=d[cur^1][j-1][0 ];p 2=d[cur^1][j-1][1]-a[i];if ((P1<MINP1) | | ((P1==MINP1) && (P2>MINP2))) {minp1=p1;minp2=p2;}} Else{p1=d[cur^1][j-1][0]+1;p2=v-a[i];if ((P1<MINP1) | | ((P1==MINP1) && (P2>MINP2))) {minp1=p1;MINP2=P2;}} D[CUR][J][0]=MINP1;D[CUR][J][1]=MINP2;}} Ans=0;for (i=n;i>=1;i--) {if (d[cur][i][0]<=m) {ans=i;break;}} printf ("%d\n", ans); if (QI!=PI) {printf ("\ n");}} return 0;}
UVA 473-raucous Rockers (DP)