DP exercise - weights weigh

DP exercise - weights weigh

0. summary


Get to the key point firstly, the article comes from LawsonAbs!


  • Not dull! Do not think that dp is only suitable for solving the maximum, minimum types of problems. While the calculation of the minimum and maximum values, but also to retain the process reaches the most value, the process data is sometimes what we need.

1. The meaning of problems

Are given quality 1-nof each of a weight, determined by the weight of the n number of weights can be weighed out. Examples are as follows.
If there are three weights, i.e. weight, respectively 1,2,3, then it can be said that 6 different weight. Respectively 1,2,3,4,5,6.

1 2 3

2. Analysis

2.1 uses dp

Array f[i]=1represents the weight i can be called up, or that can not be said to weight i.
Double loop can be calculated for all up weight i.
(In fact, if you do not give dp crown hat on this algorithm, you may feel is not so difficult to understand.) A little think about it, you know it is logical and can find the answer.

2.2 algorithm steps
  • step 1. The first weight for loop, each article placed on a 1-n
  • step 2. second heavy forcycle from maximum weight maxWto enumerate 0, if f[j-arr[i]]=1, represents j-arr[i]the weight up, then standing j-arr[i]base, plus arr[i], j up to the. So f [j] = 1.
  • step 3. According to the above in this order and so on, and finally from 1 to maxW, find the number i is f [i] = 1, is the final result.

3. Code

#include<iostream>
using namespace std; 
const int maxN = 20;
const int maxW = 1000;//限制最大可称重量
 
int n,m;//从n个数中选择m个 
int arr[maxN];

int main(){	
	cin >> n;
	//有重量为1,2,3,...n 的硬币各一枚 
	for(int i = 1;i <= n;i++){
		arr[i] = i;
	}
	int f[maxW];
	fill(f,f+maxW,0);
	f[0] = 1;
	
	//dp获取可称重的个数 
	for(int i = 1; i <= n;i++) {		
		for(int j = maxW;j >= 0;j--){			
			if(j >= arr[i] && f[j-arr[i]] == 1){//如果重量j大于砝码 arr[i]的重量 				 
				f[j] = 1;
			}
		}
	}
	
	int cnt = 0;
	for(int i = 1;i<= maxW;i++){
		if(f[i] == 1){
			cnt ++;
		}
	}
	cout << cnt <<"\n"; 	
}
Published 954 original articles · won praise 307 · Views 1.12 million +

Guess you like

Origin blog.csdn.net/liu16659/article/details/104703708
Recommended