UVA 100题解

因为今天才开始刷UVA的题目,首先肯定是拿到简单题试试啦,这题水题一个,首先数据量很大,达到了1000000,如果写个函数每次对区间内的数判断循环数的话超时妥妥的,所以首先直接开个大数组,保存下来每个数字的循环次数,然后就是利用好已有的数字的循环次数来减少时间消耗,代码如下:

#include <iostream>
#include <cstdio>

using namespace std;

int a[1000001];

int main(){
	int n1,n2,max_len,cycle;
	a[1] = 1;
	a[2] = 2;
	for(int i=3;i<1000001;i++){
		cycle = 0;
		long long temp = i;
		while(1){
			if(temp % 2 == 0){
				temp /= 2;
				cycle++;
			}
			else{
				temp = temp*3 + 1;
				cycle++;
			}
			if(temp<i){
				a[i] = cycle + a[temp]; 
				break;
			}
		}
	}
	while(scanf("%d%d",&n1,&n2)!=EOF){
		max_len = -1;
		int a1,b1;
		if(n1>n2){
			a1 = n2;
			b1 = n1;
		}
		else{
			a1 = n1;
			b1 = n2;
		}
		for(int i=a1;i<=b1;i++){
			if(a[i]>max_len)
				max_len = a[i];		
		}
		cout<<n1<<" "<<n2<<" "<<max_len<<endl;
	}
	//cout<<cal(22)<<endl;
	return 0;
} 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章