题意:
用n根火柴棒搭出数字,求这个数能被m整除的最大值
思路:
递推的式子是newi=i+num[k][根数], newj=(j*10+k)%m[余数]
dp[newi][newj] = max(dp[i][j]+1, dp[newi][newj]);
那么ans是只针对余数为0的情况
出发点是dp[0][0],结尾点是dp[i][0],之间必定是会得出一条等差数列(d=1)铺成的路
所以就有dp[newi][newj]==d[i][j]+1, path[i][j] = k;
<pre name="code" class="cpp">#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
const int maxn = 110;
const int maxm = 3010;
int dp[maxn][maxm], path[maxn][maxm];
int m, n;
int ans;
int num[10] = {6,2,5,5,4,5,6,3,7,6};
void deal() {
for(int i=0; i<n; i++)
for(int j=0; j<m; j++) {
if(dp[i][j]>=0) //已经得出
for(int k=9; k>=0; k--) {
if(num[k]+i<=n){
int newi = i+num[k];
int newj = (j*10+k)%m;
if(dp[i][j]+1>dp[newi][newj]) dp[newi][newj] = dp[i][j]+1;
if(dp[newi][newj]>ans && newj==0) ans = dp[newi][newj];
}
}
}
}
void find() {
memset(path, -1, sizeof(path));
for(int i=n; i>=0; i--)
for(int j=0; j<m; j++)
if(dp[i][j]>=0) {
if(dp[i][j]==ans && j==0) {
path[i][j] = 10;
continue;
}
for(int k=9; k>=0; k--)
if(i+num[k]<=n) {
int newi = i+num[k], newj = (j*10+k)%m;
if(dp[newi][newj]==(dp[i][j]+1) && path[newi][newj]>=0) {
path[i][j] = k;
break;
}
}
}
}
void print() {
int i, j, k, l;
if(ans>0) {
i = 0, j = 0;
while(path[i][j] != 10) {
k = i+num[path[i][j]];
l = (j*10+path[i][j])%m;
printf("%d", path[i][j]);
i = k;
j = l;
}
printf("\n");
}
else if(n>=num[0]) printf("0\n");
else printf("-1\n");
}
int main() {
int kase = 1;
while(scanf("%d", &n) != EOF && n) {
scanf("%d", &m);
printf("Case %d: ", kase++);
memset(dp, -1, sizeof(dp));
dp[0][0] = 0, ans = 0;
deal();
find();
print();
}
return 0;
}
Bigger is Better
最新推荐文章于 2017-03-22 13:32:41 发布