DP: 0-1 backpack problem

table of Contents

HDU 2602 Bone Collector

HDU 3466 Proud Merchants

UVA 12563 Jin Ge Jin Qu hao


HDU 2602 Bone Collector

topic:

Description

Many years ago , in Teddy’s hometown there was a man who was called “Bone Collector”. This man like to collect varies of bones , such as dog’s , cow’s , also he went to the grave … 
The bone collector had a big bag with a volume of V ,and along his trip of collecting there are a lot of bones , obviously , different bone has different value and different volume, now given the each bone’s value along his trip , can you calculate out the maximum of the total value the bone collector can get ? 

Input

The first line contain a integer T , the number of cases. 
Followed by T cases , each case three lines , the first line contain two integer N , V, (N <= 1000 , V <= 1000 )representing the number of bones and the volume of his bag. And the second line contain N integers representing the value of each bone. The third line contain N integers representing the volume of each bone.

Output

One integer per line representing the maximum of the total value (this number will be less than 2  31).

Sample Input

1
5 10
1 2 3 4 5
5 4 3 2 1

Sample Output

14

This topic is just the simplest 0-1 backpack problem, stop talking, just go to the code

Code:

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
 
int value[1001], volume[1001], ans[1001];
 
int main()
{
	int cas;
	cin >> cas;
	int N, V;
	while (cas--)
	{
		cin >> N >> V;
		memset(ans, 0, sizeof(ans));
		for (int i = 1; i <= N; i++)cin >> value[i];
		for (int i = 1; i <= N; i++)cin >> volume[i];
		for (int i = 1; i <= N; i++)for (int j = V; j >= volume[i]; j--)
			ans[j] = max(ans[j], ans[j - volume[i]] + value[i]);
		cout << ans[V] << endl;
	}
	return 0;
}

HDU 3466 Proud Merchants

topic:

Description

Recently, iSea went to an ancient country. For such a long time, it was the most wealthy and powerful kingdom in the world. As a result, the people in this country are still very proud even if their nation hasn’t been so wealthy any more. 
The merchants were the most typical, each of them only sold exactly one item, the price was Pi, but they would refuse to make a trade with you if your money were less than Qi, and iSea evaluated every item a value Vi. 
If he had M units of money, what’s the maximum value iSea could get? 

Input

There are several test cases in the input. 
Each test case begin with two integers N, M (1 ≤ N ≤ 500, 1 ≤ M ≤ 5000), indicating the items’ number and the initial money. 
Then N lines follow, each line contains three numbers Pi, Qi and Vi (1 ≤ Pi ≤ Qi ≤ 100, 1 ≤ Vi ≤ 1000), their meaning is in the description. 
The input terminates by end of file marker. 

Output

For each test case, output one integer, indicating maximum value iSea could get. 

Sample Input

2 10
10 15 10
5 10 5
3 10
5 10 5
3 5 6
2 7 3

Sample Output

5
11

This problem is very close to the 0-1 knapsack problem. One difference is that the capacity of q is needed to load things of the size p.

We need to modify this difference in two places.

First, the two-layer for loop for refreshing the watch, the inner loop should be bounded by q instead of p.

To be honest, at first, I thought it was enough to change this place, but the result was not correct for the input example 3 10 5 10 5 3 5 6 2 7 3 given in the question.

Then I thought about it, because the method of refreshing the watch of a 0-1 backpack is to select the back items first, and then select the front items.

Although for the 0-1 knapsack problem, any order is the same,

But in this question, after choosing 3 5 6 first, you cannot choose 5 10 5.

If you choose 5 10 5 first, then you can choose 3 5 6.

Then how to solve the order problem?

Definitely not enumerating the sequence! After all, there are 500 items.

The order of this topic is not difficult, that is, calculate the qp value of each item, and then sort in this order.

If the qp of 2 items are the same, we don't even care about the order of these 2 items!

I'm not quite clear about the specific principles, but it feels obvious anyway.

Simply put, whether j can be installed after i is installed depends on whether the backpack has pi+qj, and whether i can be installed after j is installed depends on whether the backpack has pj+qi.

Because the total value of the two orders is the same, we should choose the smaller number of pi+qj and pj+qi (the corresponding order).

This means choosing items with larger qp to load into the backpack first.

Because the refresh table is loaded from the following items first, the items must be sorted in ascending order of qp.

For how to find a greedy strategy like qp, you can look at a similar topic HDU 4864 Task 

Code:

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
 
int n, m;
struct node
{
	int p;
	int q;
	int v;
};
 
node nod[501];
int r[5001];
 
bool cmp(node a, node b)
{
	return a.q - a.p < b.q - b.p;
}
 
int main()
{
	while (cin >> n >> m)
	{
		for (int i = 1; i <= n; i++)cin >> nod[i].p >> nod[i].q >> nod[i].v;
		sort(nod + 1, nod + n, cmp);
		memset(r, 0, sizeof(r));
		for (int i = 1; i <= n; i++)for (int j = m; j >= nod[i].q; j--)if (r[j] < r[j - nod[i].p] + nod[i].v)r[j] = r[j - nod[i].p] + nod[i].v;
		cout << r[m] << endl;
	}	
	return 0;
}

UVA 12563 Jin Ge Jin Qu hao

topic:

There is one very popular song called Jin Ge Jin Qu(). It is a mix of 37 songs, and is extremely long (11 minutes and 18 seconds) — I know that there are Jin Ge Jin Qu II and III, and some other unofficial versions. But in this problem please forget about them.

Why is it popular? Suppose you have only 15 seconds left (until your time is up), then you should select another song as soon as possible, because the KTV will not crudely stop a song before it ends (people will get frustrated if it does so!). If you select a 2-minute song, you actually get 105 extra seconds! ....and if you select Jin Ge Jin Qu, you’ll get 663 extra seconds!!! Now that you still have some time, but you’d like to make a plan now. You should stick to the following rules:

  •  Don’t sing a song more than once (including Jin Ge Jin Qu). 
  •  For each song of length t, either sing it for exactly t seconds, or don’t sing it at all. 
  •  When a song is finished, always immediately start a new song.

Your goal is simple: sing as many songs as possible, and leave KTV as late as possible (since we have rule 3, this also maximizes the total lengths of all songs we sing) when there are ties.


Input 

The first line contains the number of test cases T (T ≤ 100). Each test case begins with two positive integers n, t (1 ≤ n ≤ 50, 1 ≤ t ≤ 10^9), the number of candidate songs (BESIDES Jin Ge Jin Qu) and the time left (in seconds). The next line contains n positive integers, the lengths of each song, in seconds. Each length will be less than 3 minutes — I know that most songs are longer than 3 minutes. But don’t forget that we could manually “cut” the song after we feel satisfied, before the song ends. So here “length” actually means “length of the part that we want to sing”.
It is guaranteed that the sum of lengths of all songs (including Jin Ge Jin Qu) will be strictly larger than t.


Output
For each test case, print the maximum number of songs (including Jin Ge Jin Qu), and the total lengths of songs that you’ll sing.


Explanation: 

In the first example, the best we can do is to sing the third song (80 seconds), then Jin Ge Jin Qu for another 678 seconds. In the second example, we sing the first two (30+69=99 seconds). Then we still have one second left, so we can sing Jin Ge Jin Qu for extra 678 seconds. However, if we sing the first and third song instead (30+70=100 seconds), the time is already up (since we only have 100 seconds in total), so we can’t sing Jin Ge Jin Qu anymore!
 

Sample Input

3 100

60 70 80 

3 100

30 69 70


Sample Output
Case 1: 2 758 

Case 2: 3 777

 

This topic is a variant of the 0-1 knapsack problem.

In fact, it is equivalent to leaving the last second to sing the golden song, and then asking how many songs you can sing in the remaining time.

At the same time, in the case of guaranteeing the maximum number of singing, ask for the maximum time for singing.

My idea is to consider the first m songs to choose n, how long can be sung in time t, and solve this problem recursively.

Because there are three parameters, a three-dimensional array is required to record the calculated results.

My code:

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
 
int list[55];
int times[55][55][9005];
int sum;
 
int f(int m, int n, int t)		//前m个歌选n个,在时间t内可以唱多久
{
	if (t >= sum)return sum;
	if (t < 0 || m < n)return -1234567890;
	if (n == 0)return 0;
	if (t == 0)return -1234567890;
	if (m == 1)
	{
		if (list[1] <= t)return list[1];
		return -1234567890;
	}
	if (times[m][n][t] >= 0)return times[m][n][t];
	int a = f(m - 1, n, t);
	int b = f(m - 1, n - 1, t - list[m]) + list[m];
	times[m][n][t] = (a > b) ? a : b;
	return times[m][n][t];
}
 
int main()
{
	int cas;
	int n, t;
	cin >> cas;
	int num, temp;
	for (int i = 1; i <= cas; i++)
	{
		sum = 0;
		cin >> n >> t;
		for (int i = 1; i <= n; i++)
		{
			cin >> list[i];
			sum += list[i];
		}
		sort(list + 1, list + 1 + n);
		num = 0;
		temp = t - 1;
		for (int i = 1; i <= n; i++)
		{
			temp -= list[i];
			if (temp < 0)break;
			num++;
		}
		memset(times, -1, sizeof(times));
		cout << "Case " << i << ": " << num + 1 << " " << f(n, num, t - 1) + 678 << endl;
	}
	return 0;
}

There should be no logical problems with this code, and I am not sure, but I tested a lot of data without any problems.

However, the OJ failed to pass, and the result was a timeout. I think it should be a problem of efficiency.

Although dynamic programming will not do repeated calculations, sometimes there will be invalid calculations.

And my idea is not very good, so there should be a lot of useless calculations.

My new idea:

Treat it as a 0-1 backpack problem.

The total value of all songs is: the more songs, the higher the value. When the number of songs is fixed, the total time will be higher.

Understand value as a variable defined by the two factors of quantity and time.

Note that the idea of ​​hashing is used here!

In other words, define the value of a song as time + 180

Code:

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
 
int list[55];
int times[18005];
int sum;
 
int main()
{
	int cas;
	int n, t;
	cin >> cas;
	int num, temp;
	for (int i = 1; i <= cas; i++)
	{
		sum = 0;
		cin >> n >> t;
		for (int i = 1; i <= n; i++)
		{
			cin >> list[i];
			sum += list[i];
		}
		sort(list + 1, list + 1 + n);
		num = 0;
		temp = t - 1;
		for (int i = 1; i <= n; i++)
		{
			temp -= list[i];
			if (temp < 0)break;
			num++;
		}				
		cout << "Case " << i << ": " << num + 1 << " ";
		if (t>sum)cout << sum + 678 << endl;
		else
		{
			for (int i = 1; i <= n; i++)list[i] += 180;	//哈希
			t += (180 * num - 1);
			memset(times, 0, sizeof(times));
			for (int i = 1; i <= n; i++)
			{
				for (int j = t; j >= list[i]; j--)
				{
					if (times[j] < times[j - list[i]] + list[i])times[j] = times[j - list[i]] + list[i];
				}
			}
			cout << times[t] + 678 - 180 * num << endl;
		}		
	}
	return 0;
}

It's a pity that wrong answer thinks about it carefully. It is true. Even if you define the value in this way, there is no guarantee that the value of 3 songs will be greater than the value of 2 songs.

Finally, I finally figured it out. I still use the 0-1 backpack method to swipe the array, but there are only two.

Code:

#include<iostream>
#include<string.h>
 
using namespace std;
 
int list[55];
int num[9005];
int times[9005];
int sum;
 
int main()
{
	int cas;
	int n, t;
	cin >> cas;
	for (int i = 1; i <= cas; i++)
	{
		sum = 0;
		cin >> n >> t;
		for (int i = 1; i <= n; i++)
		{
			cin >> list[i];
			sum += list[i];
		}				
		cout << "Case " << i << ": ";
		if (t > sum)cout << n + 1 << " " << sum + 678 << endl;
		else
		{
			memset(num, 0, sizeof(num));
			memset(times, 0, sizeof(times));
			for (int i = 1; i <= n; i++)
			{
				for (int j = t-1; j >= list[i]; j--)
				{
					if (num[j] == num[j - list[i]] + 1)
					{
						if (times[j] < times[j - list[i]] + list[i])times[j] = times[j - list[i]] + list[i];
					}
					else if (num[j] < num[j - list[i]] + 1)
					{
						num[j] = num[j - list[i]] + 1;
						times[j] = times[j - list[i]] + list[i];
					}
				}
			}
			cout << num[t-1] + 1 << " " << times[t-1] + 678 << endl;
		}		
	}
	return 0;
}

This code is AC.

Guess you like

Origin blog.csdn.net/nameofcsdn/article/details/113099390