CodeForces 349B Color the Fence (DP)

题意:给出1~9数字对应的费用以及一定的费用,让你输出所选的数字所能组合出的最大的数值。

析:DP,和01背包差不多的,dp[i] 表示费用最大为 i 时,最多多少位,然后再用两个数组,一个记录路径,一个记录是数字几即可。

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#include <sstream>
#define debug() puts("++++");
#define gcd(a, b) __gcd(a, b)
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;

typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e6 + 5;
const int mod = 1e6;
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
const char *de[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"};
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline bool is_in(int r, int c){
  return r >= 0 && r < n && c >= 0 && c < m;
}
int a[15];
int dp[maxn], p[maxn], path[maxn];
int cnt[15];

void print(int ans){
  memset(cnt, 0, sizeof cnt);
  while(ans != -1){
    ++cnt[path[ans]];
    ans = p[ans];
  }
  for(int i = 9; i > 0; --i)
    while(cnt[i]--)  printf("%d", i);
  printf("
");
}

int main(){
  while(scanf("%d", &n) == 1){
    memset(dp, 0, sizeof dp);
    memset(p, -1, sizeof p);
    for(int i = 1; i < 10; ++i)  scanf("%d", a+i);
    for(int i = 1; i < 10; ++i)
      for(int j = a[i]; j <= n; ++j)
        if(dp[j] < dp[j-a[i]]+1){
          dp[j] = dp[j-a[i]] + 1;
          p[j] = j - a[i];
          path[j] = i;
        }
        else if(dp[j] == dp[j-a[i]]+1 && path[j] < i){
          path[j] = i;
          p[j] = j - a[i];
        }
    if(dp[n] == 0)  puts("-1");
    else print(n);
  }
  return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/6522867.html