Recursion 3: Fork in the road-second more on March 02, 2021

Recursion 3: Fork in the road

Question source: [SSL] 1561

topic:

John's N (1≤N≤1,000,000,000) cows set out to explore the land around the ranch. They will walk along a road until they reach the three-way intersection (it can be considered that all intersections are like this). At this time, this herd of cows may be divided into two groups and continue walking along the next two roads respectively. If they walk to the three-way junction again, it is still possible to continue to split into two groups and continue walking.

The way cows split is very strange: if this herd of cows can be accurately divided into two parts, and the number of cows in the two parts is exactly K (1≤K≤1000), then the herd will split at the intersection of three forks. Otherwise, the herd will not split, and they will all stay here and graze peacefully. Please calculate how many herds of cows will be grazing peacefully in the end.

Enter
two integers N and K.

Output the
final number of herds.

Input sample
6 2

Sample output
3

Ideas:

Although this question seems to be very simple on the surface, it is actually that simple .
In other words, the idea of ​​this question is quite awkward, it seems quite simple (nk)/2 based on the condition of grouping, but in fact there are some details that need to be paid attention to.
Two conditions for grouping: 1.nk must be an even number; 2.nk must be> 0, even =0, otherwise it will enter an endless loop. After all, 0 cows can't be regarded as a group .

Code:

Show two pieces of code that are so different because of the difference in details:

Error code↓

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
ULL n,k,k2;

ULL dg(ULL x)
{
    
    
	if((x-k)%2!=0||x<=k)
		return 1;
	else
		return dg((x/2)+k2)+dg((x/k)-k2);
} 
int main()
{
    
    
	cin>>n>>k;
	k2=k/2;
	cout<<dg(n);
	return 0;
}

Insert picture description here

Positive solution code↓

#include<bits/stdc++.h>
using namespace std;
int n,k,h;

void dg(int x)
{
    
    
	if((x-k)>0&&(x-k)%2==0)
	{
    
    
		dg((x-k)/2);
		dg((x+k)/2);
	}
	else
		h++;
} 
int main()
{
    
    
	cin>>n>>k;
	dg(n);
	cout<<h;
	return 0;
}

Insert picture description here
Facts have proved: the details are very important and must not be careless. In addition, if you can push the answer yourself, test it a few more times before submitting it, otherwise it won't be so miserable and it will cost you very much.

Guess you like

Origin blog.csdn.net/SSL_wyd/article/details/114291430