寒冰王座(完全背包)

传送原题
在这里插入图片描述

  • 一道完全背包问题
  • 只要把01背包的j反过来就行
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<math.h>
#include<string.h>
#include<sstream>
using namespace std;
int a[] = {150,200,350};
int dp[10005];
int main() {
	ios::sync_with_stdio(false);
	int t, money;
	cin >> t;
	while(t --){
		memset(dp,0,sizeof(dp));
		cin >> money;
		for(int i = 0; i < 3; i ++)
			for(int j = a[i]; j <= money; j ++)
			dp[j] = max(dp[j], dp[j-a[i]] + a[i]);
		cout << money - dp[money] << endl;
	}
    return 0;
}


  • 然后我做了一个小优化,速度可能快了50倍,也可能没什么软用
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<queue>
#include<math.h>
#include<string.h>
#include<sstream>
using namespace std;
int a[] = {150,200,350};
int dp[10005];
int main() {
	ios::sync_with_stdio(false);
	int t, money;
	cin >> t;
	while(t --){
		memset(dp,0,sizeof(dp));
		int Max = 0;
		cin >> money;
		for(int i = 0; i < 3; i ++)
			for(int j = a[i]; j <= money; j += 50){//最大公因数
				dp[j] = max(dp[j], dp[j-a[i]] + a[i]);
				Max = max(Max,dp[j]);//防止出现不是整数啥的
			}
			
		cout << money - Max << endl;
	}
    return 0;
}

发布了46 篇原创文章 · 获赞 5 · 访问量 2655

猜你喜欢

转载自blog.csdn.net/xuhang513/article/details/105301326