Enter the "Basic Training of Deep Search" and step into the palace of C++ algorithms (5)

[Search and Backtracking Algorithm] Salesperson’s Trouble (Standard IO)

Time limit: 1000 ms Space limit: 262144 KB Specific limits  

Topic description:

An ice cream shop has just opened. There are 2×N people outside buying 1 yuan of ice cream. Half of them are holding a 2 yuan ticket, and the other half are holding a 1 yuan ticket. The salesperson was careless and did not prepare any change. How should these 2×N people line up in order to prevent the problem of finding money during the sale? Please help the salesperson find the total quantity of all plans.

enter:

An integer N (N≤15).

Output:

The total number of plans is M.

Sample input:

4

Sample output:

14

        This is the fifth question. Xiaohang read the question and quickly started thinking.

Xiaohang thought (thinking):

1. It can be done by simulation method

2. Starting from the first person, simulate in sequence until reaching half n

3. Those who bring one yuan should be ranked before those who bring two yuan. Therefore, in the plan, the number of people who have paid and brought one yuan must be equal to or smaller than the number of people who have paid and brought two yuan. Otherwise, return immediately.

4. When the limit point is exceeded (that is, n is greater than twice), you must return immediately.

5. You can use two global variables to store "the number of people who have paid with one yuan" and "the number of people who have paid with two yuan", and use local variables to indicate how many people have paid currently.

Xiaohang wrote (program)

#include<iostream>
using namespace std;
int n,sum,p1,p2;
void dg(int x)
{
	if(p1>n||p2>n)
    {
        return;
    }
	if(x==2*n)
	{
		sum++;
		return;
	}
	else
	{
		if(p2>p1)
		{
			return;
		}
		else
		{
			p1++;
			dg(x+1);
			p1--;
			p2++;
			dg(x+1);
			p2--;
		}
	}
}
int main()
{
	cin>>n;
	dg(0);
	cout<<sum;
}

Obviously, the result is:

        100 points!

However, there was not much time. Xiaohang did not have time to finish the fifth question, so he had to write it randomly. one

Manifest manifest! 

"Ding——" The game ended, and Xiaoliang entered the top 100 with a score of 500 points.

"Students, don't be discouraged if you didn't do well in the exam, because together we are entering the "Basic Training of Deep Search" and entering the palace of C++ algorithms !" The host said, "By the way, remember to write a summary of the competition and change the questions after you go home !" "


hint:

Pay attention to time during the competition and don't make the same mistake as Xiaohang; it is best to write a summary of the competition after the competition and change the questions, so that you can make better progress!

Guess you like

Origin blog.csdn.net/aliyonghang/article/details/122574098