PAT乙级1030

PAT乙级1030

马上读研了,拿pat复习一下吸语言。

题目

给定一个正整数数列,和正整数 p,设这个数列中的最大值是 M,最小值是 m,如果 Mm**p,则称这个数列是完美数列。

现在给定参数 p 和一些正整数,请你从中选择尽可能多的数构成一个完美数列。

输入格式:

输入第一行给出两个正整数 Np,其中 N(≤105)是输入的正整数的个数,p(≤109)是给定的参数。第二行给出 N 个正整数,每个数不超过 109。

输出格式:

在一行中输出最多可以选择多少个数可以用它们组成一个完美数列。

输入样例:

10 8
2 3 20 4 5 1 6 7 8 9

输出样例:

8

错误

测试点3超时

暴力破解,导致超时。

#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>

/*
10 8
2 3 20 4 5 1 6 7 8 9

10 101
2 3 20 4 5 1 6 7 8 100

3 5
5 5 5

1 1
1
*/

using namespace std;

//statement code
long i,N,p;
long input[1000000];

//function section
int robustness_check1(){//robustness function1
	return 0;
}

void print_result(){
	sort(input,input+N);
	long count = 0;
	// int min_index = 0;
	long max_index = N-1;
	long temp_count;
	for(i = 0 ; i < N ; i++){
		max_index = N-1;
		while((input[i] * p) <input[max_index]){
			max_index--;
		}
		if(count < (max_index - i + 1)){
			count = max_index - i + 1;
		}
	}
	printf("%ld", count);
}

int main(){
	//input code
	scanf("%ld %ld",&N,&p);
	for( i = 0 ; i < N ; i++){
		long temp;
		scanf("%ld",&temp);
		input[i] = temp;
	}
	//robustness code
	//function code
	print_result();
	return 0;
}

代码

对算法进行了小优化。

#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>

/*
10 8
2 3 20 4 5 1 6 7 8 9

10 101
2 3 20 4 5 1 6 7 8 100

3 5
5 5 5

2 1
1 4
*/

using namespace std;

//statement code
long i,N,p;
long input[1000000];

//function section
int robustness_check1(){//robustness function1
	return 0;
}
void print_result(){
	sort(input,input+N);
	long count = 0;
	// int min_index = 0;
	long max_index = 0;
	long temp_count;
	for(i = 0 ; i < N ; i++){
		while(max_index < N && (input[i] * p) >= input[max_index])
			max_index++;
		if(count < (max_index - i ))
			count = max_index - i ;
	}
	printf("%ld", count);
}
int main(){
	//input code
	scanf("%ld %ld",&N,&p);
	for( i = 0 ; i < N ; i++){
		long temp;
		scanf("%ld",&temp);
		input[i] = temp;
	}
	//robustness code
	//function code
	print_result();
	return 0;
}

总结

  • 需要注意算法的设计不能超时
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值