PAT 1005 continues (3n + 1) guess

Kharazi (Callatz) conjecture description has been given in 1001. In this topic, the situation is somewhat more complicated.

When we verify Kharazi guess when, in order to avoid double counting, the number can be recorded at each recursive encountered. For example, when n = 3 for verification, we need to calculate 3,5,8,4,2,1, then when we verify the n = 5,8,4,2, it can be determined directly Kharazi guess authenticity, without double counting, because it has the number 4 3 when encountered in the validation, we are called 5,8,4,2 3 "coverage" of the number. We call a number in a column n is the number of "key number", if n can not be covered by other figures in the series.

Now given to a series of numbers to be verified, we only need to verify a few key number of them, you do not have to be repeated to verify the remaining numbers. Your task is to find these key figures, according to output them in descending order.

Input formats:

Positive integer value of n (1 <n≤100) Each test comprises a test input, a first row is given a positive integer K (<100), the second line gives the K different from each other to be verified , separated by spaces between numbers.

Output formats:

Each test case output per line, in descending order of output key figures. Separated by a space between the numbers, but after a row last number with no spaces.

Sample input:

6
3 5 6 7 8 11

Sample output:

7 6

Ideas:

The first step: using an array B [] related to the number of labeled, for example, when n = 3 for authentication, are related to the number 3,5,8,4,2,1;

Step two: the test data using the C ++ header file agorithm sort function will be entered in ascending order;

The third step: sequentially determining whether the test data from the end of a key number, if b [a [i]] == false, then a [i] is the key number, it outputs, when the output format of the note issue.

code show as below:

#include<iostream>
#include<algorithm>
using namespace std;

bool b[100000];

void f(int n){
	//3n+1猜想
	while(n!=1){
		if(n%2){
			//n为奇数
			n=(3*n+1)/2;
			b[n]=true; 
		}
		else if(n%2==0){ //if(!n%2)错误,!的优先级高于n 
			n=n/2;
			b[n]=true;
		}
	} 
}

int main()
{
	int m;
	cin>>m;//输入m个数字
	int a[1000];//m个数字存到数组中去 
	for(int i=0;i<m;i++)
	{
		cin>>a[i]; 
		f(a[i]);//暴力标记 
	}
    sort(a,a+m);//sort(首元素地址,尾元素的下一个地址,比较函数);升序排序 
    /*for(int i=m-1;i>=0;i--)
    {
    	if(!b[a[i]]){//判断是否为关键数,没有被覆盖 
    		cout<<a[i]<<" ";//如果不是输出这个数 
		}
	}*/
	//调整格式,最后一个数字没有空格,设置一个flag标志
	//第一次只输出一个数字,之后输出空格+数字 
	int flag=0;
	for(int i=m-1;i>=0;i--)
	{
		if(!b[a[i]]){//判断是否为关键数(即没有被覆盖的数)
			if(flag==1)
				cout<<" "<<a[i];
			else{
				flag=1;
				cout<<a[i];
			}
		}
	 }
	 cout<<endl;
	return 0; 
}
Released four original articles · won praise 0 · Views 103

Guess you like

Origin blog.csdn.net/l1079823816/article/details/104024319