Greedy entry basics (loading problem, number of intervals, haffman (priority queue))

Greedy algorithm foundation (super-basic kind)

Greedy method is a problem-solving strategy. If correct, the greedy method will be easy to describe and implement

Loading problem

Given n objects, each object has a volume of mi and a unit price of pi. There is a backpack with a volume of m.
Ask how many are the most expensive. (Assuming the object can be divided).
First, we need to define the structure and an array of structures, and then sort the unit price in descending order, each time we must select the object with the largest unit price.

** Just like this example **

It was said that the Haidong Group faced difficulties in domestic and foreign affairs, and the company's veterans were only left by the XHD couple. Obviously, as a businessman struggling for many years, XHD will not sit still.
One day, when he was thinking hard and trying to solve his problems, he suddenly thought of his family heirloom. That was when the company was founded. His father gave him a gift as a gift. Father Xu explained at the time that it was not a last resort. "Isn't it the time when I need it most?" While thinking, XHD found this well-preserved kit and opened it. There was only a sentence "There is treasure in Qianren Cave at the northern foot of Hangzhou City".
Without saying a word, XHD picked up a big pocket and set off. He knew about this thousand-man cave. When he was young, his father once brought him to this hidden intersection and told him that this is a thousand-man cave. He only now understood the meaning of his father's words.
Despite the impression, XHD spent a lot of energy to find this unusually hidden hole, walked in and almost stunned, it was really dazzling! However, although there are many types of babies, the amount of each type of baby is not much. Of course, the price of each baby's unit volume is also different. baby? (Assuming that the baby can be divided, the value after division is proportional to the corresponding volume)

The Input
input contains multiple test instances. The first line of each instance is two integers v and n (v, n <100), which respectively indicate the pocket capacity and the type of baby. The next n lines each contain 2 integer pi and mi (0 <pi, mi <10) respectively represent the unit price and corresponding volume of a certain baby, and the input ends when v is 0.

Output
For each test case, output a maximum number of baby XHD value can be retrieved, one row for each instance of the output.

Sample Input
2 2
3 1
2 3
0

Sample Output
5

#include<iostream>
#include<algorithm>
using namespace std;
struct node {//物品结构体
	int pi;
	int mi;
}arr[110];
bool cmp(node a, node b) {
	return a.pi > b.pi;
}
int main() {
	int v, n;
	while (cin >> v) {
		if (v == 0)break;//结束输入
		else {
			cin >> n;
			for (int i = 0; i < n; i++) {
				cin >> arr[i].pi >> arr[i].mi;
			}int sum = 0;
			sort(arr, arr + n, cmp);//保证下面每一步都是最优解
			for (int i = 0; i < n; i++) {
				if (v > arr[i].mi) {//可以完全装下目前的商品
					sum = sum + arr[i].mi*arr[i].pi;
					v = v - arr[i].mi;
				}
				else {//这个物品需要分割
					sum = sum + arr[i].pi*v;
					break;//已经装满
				}
			}
			cout << sum << endl;
		}
	}
	return 0;
}

Title link

Select disjoint intervals

There are n open intervals on the number line. The starting point is ai and the ending point is bi. Try to select multiple intervals so that the selected intervals have no common points.

First, suppose there are two intervals n and m. If these two intervals,
n __________________
m _________
m is completely inside n. At this time, it is obvious to choose m is the best choice, because not only can choose an interval, but also can save nm free interval.

a 1 ___

b____________… c ___________ At
this time,
if interval a and interval b do not intersect, then it is wise to choose interval a. If interval a and interval b intersect, then it is still wise to choose interval a.
Because the part before 1 in the interval a has no effect, only the part that is greater than 1 has an effect on the subsequent selection, and this influential part is significantly smaller than b. Therefore, choose a.

Example question
This summer is not AC HDU-2037
"Not this summer is AC?"
"Yes."
"So what are you doing?"
"Look at the World Cup, idiot!"
"@ # $% ^ & *%…"

Indeed, the World Cup is coming, and the fans ’festival is also coming. It is estimated that many ACMers will also abandon the computer and run to the TV.
As a fan, you must want to watch as many complete games as possible. Of course, as a good young man in the new era, you will definitely watch some other programs, such as news broadcast (never forget to care about national events), very 6 + 7, super Girls, and Wang Xiaoya's "Happy Dictionary", etc., assuming that you already know the broadcast schedule of all the TV programs you like to watch, will you make reasonable arrangements? (The goal is to watch as many complete programs as possible.)
Input
data contains multiple test instances. The first line of each test instance has only an integer n (n <= 100), indicating the total number of programs you like to watch, and then n lines of data, each line includes two data Ti_s, Ti_e (1 <= i <= n), respectively representing the start and end time of the ith program, in order to simplify the problem, each time is represented by a positive integer. n = 0 means the input is over and no processing is done.
Output
For each test case number, complete output can see the television program, the output of each test case in a separate line.
Sample Input
12
1 3
3 4
0 7
3 8
15 19
15 20
10 15
8 18
6 12
5 10
4 14
2 9
0
Sample Output
5
topic link

#include<iostream>
#include<algorithm>
using namespace std;
struct node{//节目
	int sx, ex;
}arr[110];
bool cmp(node a, node b) {
	return a.ex < b.ex;
}
int main() {
	int n;
	while (cin >> n) {
		if (n == 0)break;
		else {
			for (int i = 0; i < n; i++) {
				cin >> arr[i].sx >> arr[i].ex;
			}sort(arr, arr + n, cmp);//对结束时间进行排序
			int count = 1;//需要输出的答案
			int cur = arr[0].ex;//用来连接
			for (int j = 1; j < n; j++) {//第j个可不可以选择
				if (arr[j].sx >= cur) {//第j个可以选择
					cur = arr[j].ex;//更新
					count++;
				}
			}cout << count << endl;
		}
	}
	return 0;
}

Huffman coding

Problem description
  Huffman tree has a wide range of applications in coding. Here, we only care about the construction process of Huffman tree.
  Given a list of numbers {pi} = {p0, p1,…, pn-1}, the process of constructing a Huffman tree with this list of numbers is as follows:
  1. Find the two smallest numbers in {pi}, set to pa and pb, Remove pa and pb from {pi}, then add their sum to {pi}. The cost of this process is recorded as pa + pb.
  2. Repeat step 1 until there is only one number left in {pi}.
  In the above operation process, all costs are added together to obtain the total cost of constructing the Huffman tree.
  Task for this problem: For a given sequence, please find the total cost of constructing a Huffman tree with that sequence.

For example, for the sequence {pi} = {5, 3, 8, 2, 9}, the construction process of the Huffman tree is as follows:
  1. Find the smallest two numbers in {5, 3, 8, 2, 9}, which are 2 and 3, delete them from {pi} and add 5 to get {5, 8, 9, 5}, the cost is 5.
  2. Find the smallest two numbers in {5, 8, 9, 5}, 5 and 5, remove them from {pi} and add 10 to get {8, 9, 10}, the cost is 10 .
  3. Find the smallest two numbers in {8, 9, 10}, which are 8 and 9, delete them from {pi} and add 17 to get {10, 17}, the cost is 17.
  4. Find the two smallest numbers in {10, 17}, which are 10 and 17, remove them from {pi} and add 27 to get {27}, the cost is 27.
  5. Now, there is only one number 27 left in the sequence. The construction process ends, and the total cost is 5 + 10 + 17 + 27 = 59.
Input format
  The first line of input contains a positive integer n (n <= 100).
  Next are n positive integers, representing p0, p1,…, pn-1, each number not exceeding 1000.
Output format
  Output the total cost of constructing the Huffman tree using these numbers.
Sample input
5
5 3 8 2 9
Sample output
59

#include<iostream>
#include<queue>
using namespace std;
int main() {
	priority_queue<int, vector<int>, greater<int > >q;//定义一个优先队列
	int n, s;
	cin >> n;
	while (n--) {
		cin >> s;
		q.push(s);
	}
	int a, b;
	int ans = 0;
	while(q.size()!=1){
		a = q.top();
		q.pop();
		b = q.top();
		q.pop();
		q.push(a + b);
		ans += a + b;
	}
	cout << ans<< endl;
	return 0;
}

…ended…

Published an original article · Liked 0 · Visits 7

Guess you like

Origin blog.csdn.net/weixin_44605812/article/details/105632588