PAT(B) 1005. 继续(3n+1)猜想

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;

vector<int> vec[105];

int cmp(int a,int b)
{
	return a>b;
}

int main()
{
	int k,i,j,l;
	for(i=2;i<=100;i++)
	{
		vec[i].clear();
		vec[i].push_back(i);
		int x=i;
		while(x!=1)
		{
			if(x%2)
			{
				x=(3*x+1)/2;
			}
			else
			{
				x=x/2;
			}
			vec[i].push_back(x);
		}
	}
	int ans[105];
	int pos;
	int Hash[10005];
	while(scanf("%d",&k)==1)
	{
		pos=0;
		memset(Hash,0,sizeof(Hash));
		for(i=0;i<k;i++)
		{
			int n;
			scanf("%d",&n);
			if(Hash[n]==0)
			{
				ans[pos++]=n;
				for(j=0;j<vec[n].size();j++)
				{	
					Hash[vec[n][j]]=1;
					for(l=0;l<pos-1;l++)
					{
						if(ans[l]==vec[n][j])
							ans[l]=-100;
					}
				}
			}
		}
		sort(ans,ans+pos,cmp);
		for(i=0;i<pos;i++)
		{
			if(i==0)
			{
				printf("%d",ans[i]);
			}
			else
			{
				if(ans[i]>0)
					printf(" %d",ans[i]);
			}
		}
		printf("\n");
	}
	return 0;
}


你可能感兴趣的:(pat)