poj1717 DP

A得很艰辛啊,虽然看上去很简单,但还是要整理好思路,而且有很多地方要注意细节!

#include <iostream>
#include <cmath>
using namespace std;
#define oo 10000000
int gap,x,y,a[1010],dp[12010][2],p,q,j,jl,n;
int main() {
    while (~scanf("%d",&n)) {
          gap = 6000;
          for (int i=1;i<=n;i++) {
              scanf("%d%d",&x,&y);
              a[i] = x-y;
          }
          for (int i=0;i<=12000;i++)
              dp[i][0] = oo;
          dp[gap+a[1]][0] = 0;
          dp[gap-a[1]][0] = 1;
          if (a[1]==0) dp[gap+a[1]][0] = 0;
          q = 0;
          p = 1;
          for (int i=2;i<=n;i++) {
              for (j=0;j<=12000;j++)
                  dp[j][p] = oo;
              for (j=0;j<=12000;j++)
                  if (dp[j][q]!=oo) {
                     if ((j+a[i])<=12000) {
                        if (dp[j+a[i]][p]==oo) dp[j+a[i]][p] = dp[j][q];
                        else dp[j+a[i]][p] = min(dp[j+a[i]][p],dp[j][q]);
                     }
                     if ((j-a[i])>=0) {
                        if (dp[j-a[i]][p]==oo) dp[j-a[i]][p] = dp[j][q]+1;
                        else dp[j-a[i]][p] = min(dp[j-a[i]][p],dp[j][q]+1);
                     }    
                  }
              //for (j=5980;j<=6020;j++)
              //    printf("%d %d %d\n",i,j-gap,dp[j][p]);
              q = 1 - q;
              p = 1 - p;
          }
          p = 1 - p;
          for (j=gap;j<=2*gap;j++)
              if (dp[j][p]<oo) break;
          for (jl=gap;jl>=0;jl--)
              if (dp[jl][p]<oo) break;
          if ((j-gap)==(gap-jl)) printf("%d\n",min(dp[j][p],dp[jl][p]));
          else if ((j-gap)<(gap-jl)) printf("%d\n",dp[j][p]);
          else printf("%d\n",dp[jl][p]);
    }
    return 0;
}


你可能感兴趣的:(poj1717 DP)