计蒜客信息学入门赛 #18--C--时间复杂度小于O(n)

C:

题目:80/100,大数据部分没有通过,也不知是不是数据产生溢出的问题,也有可能是精度的偏差;

思路一:由于a+b<=c,可以根据勾股定理,pf(a+b)+pf(c)=pf(n),可以有c>=n/根号2,减少穷竭搜索;

#include<iostream>
#include<cstring>
#include<cstdio> 
#include<algorithm>
#include<cmath>
using namespace std;
int n;
double ip=1.414213;
bool check(double x){
	return x==(int)(x)?true:false;
}
void solve(){
	int ans=0;
	for(int c=(int)(n/ip)+1;c<n;c++){
		double ab=sqrt((n+c)*(n-c));
		if(check(ab))
			ans+=(int)(ab)/2;
	}
	cout<<ans<<endl;
	return;
}
int main(){
	while(cin>>n){
		solve();
	}
	return 0;
}

我们改正一下数据精度问题,一下子就过了:long long 类型

#include<iostream>
#include<cstring>
#include<cstdio> 
#include<algorithm>
#include<cmath>
using namespace std;
long long n;
double ip=1.414213;
bool check(double x){
	return x==(int)(x)?true:false;
}
void solve(){
	long long ans=0;
	for(long long c=(int)(n/ip)+1;c<=n;c++){
		double ab=sqrt((n+c)*(n-c));
		if(check(ab))
			ans+=(int)(ab)/2;
	}
	cout<<ans<<endl;
	return;
}
int main(){
	while(cin>>n){
		solve();
	}
	return 0;
}

补充:

思路二:枚举c,计算出(a+b)^2,ans/2即为答案;

这实际上是官方给出的答案,时间复杂度O(n),相比于思路一的,所用的时间就比较长,而我写的思路一需要数学公式处理,c不从1开始搜索,而是从(int)(n/ip)+1开始,时间复杂度<O(n);

#include<iostream>
#include<cstring>
#include<cstdio> 
#include<algorithm>
#include<cmath>
using namespace std;
long long n;
bool check(double x){
	return x==(int)(x)?true:false;
}
void solve(){
	long long ans=0,cnt=0;
	for(long long c=1;c<=n;c++){
		long long ab=n*n-c*c;
		ans=sqrt(ab);
		if(ans*ans==ab&&ab!=0&&ans<=c)
			cnt+=ans/2;
	}
	cout<<cnt<<endl;
	return;
}
int main(){
	while(cin>>n){
		solve();
	}
	return 0;
}
发布了226 篇原创文章 · 获赞 90 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/queque_heiya/article/details/105310571