http://acm.hdu.edu.cn/showproblem.php?pid=1407

计算方程x^2+y^2+z^2= num的一个正整数解。num为不大于10000的正整数

思路:

方法一、直接三重循环暴力 234MS

方法二、枚举x和y,对z进行二分查找。62MS

方法三、枚举x和y,对z用hash判断是否存在 15MS

方法二和方法三都是枚举x和y,但是二分查找为O(log(n))而hash为O(1)

可以看到,方法一和方法三差了十几倍!

还有就是用goto从内重循环直接跳出简洁而优雅。

方法一:直接三重循环暴力 234MS

#include<cstdio>
#include<cmath>
int res[101];
int main()
{
int n;
for(int i=1;i<=100;i++)
res[i]=i*i; while(~scanf("%d",&n))
{
for(int x=1;x<=100;x++)
for(int y=1;y<=100;y++)
for(int z=1;z<=100;z++)
if( res[x]+res[y]+res[z]==n)
{
printf("%d %d %d\n",x,y,z);
goto end;
}
end:;
}
return 0;
}

方法二:枚举x和y,对z进行二分查找。62MS

#include<cstdio>
#include<cmath>
int res[101];
int search(int n)
{
int L=1,R=101;
while(L<R)
{
int m=(L+R)>>1;
if(res[m]==n)
return m;
else if(res[m] < n)
L=m+1;
else
R=m;
}
return -1;
}
int main()
{
int n;
for(int i=1;i<=100;i++)
res[i]=i*i; while(~scanf("%d",&n))
{
for(int x=1;x<=100;x++)
{
for(int y=1;res[x]+res[y]<n;y++)
{
int z=search(n-res[x]-res[y]);
if(z!=-1)
{
printf("%d %d %d\n",x,y,z);
goto end; }
}
} end:;
}
return 0;
}

方法三:枚举x和y,对z用hash判断是否存在  15MS

#include<cstdio>
#include<cmath>
const int MAXN=10001;
int res[101];
struct HASH
{
bool exist;
int index;
}hash[MAXN];
int main()
{
int n;
for(int i=1;i<=100;i++)
{
res[i]=i*i;
hash[ res[i] ].exist=true;
hash[ res[i] ].index=i;
} while(~scanf("%d",&n))
{
for(int x=1;x<=100;x++)
{
for(int y=1;res[x]+res[y]<n;y++)
{
int id=n-res[x]-res[y];
if(hash[id].exist)
{
printf("%d %d %d\n",x,y,hash[id].index);
goto end; }
}
} end:;
}
return 0;
}

最新文章

  1. mfc release 版本 内存不足 的解决方法
  2. CALayer 易混淆的两个属性 - position和anchorPoint
  3. 黄聪:MySQL 按指定字段自定义列表排序
  4. Android Studio集成百度地图SDK
  5. HFS 2.3x 远程命令执行(抓鸡黑客末日)
  6. hdu 5340 Three Palindromes
  7. Python 字典(Dictionary) get()方法
  8. iOS Foundation框架 -2.常用集合类简单总结
  9. 【Linux高频命令专题(15)】more
  10. Java 容器相关知识全面总结
  11. 【转】WCF、WebAPI、WCFREST、WebService之间的区别
  12. HDU1163【九余数定理】【水题】
  13. Socket 由浅入深系列--------- 简单实现编程(三)
  14. PHP 类的封装和使用
  15. 搭建ejabberd集群
  16. 导出表结构到Excel 生成代码用
  17. idea当配置eclipse快捷键时,全局替换的快捷键是什么?
  18. STM8S ------ VCAP download
  19. Step7:SQL Server 多实例下的复制
  20. Device Identifier and Device DNA初识

热门文章

  1. BZOJ1835: [ZJOI2010]base 基站选址(线段树优化Dp)
  2. 一起talk C栗子吧(第三十四回:C语言实例--巧用溢出计算最值)
  3. 设计模式(7)-结构型模式-Bridge模式
  4. vue-cli(脚手架) 打包上线
  5. 有点坑爹的GDALComputeRasterMinMax函数
  6. weblogic安装(无界面静默安装)
  7. BZOJ3514: Codechef MARCH14 GERALD07加强版(LCT,主席树)
  8. BZOJ3926: [Zjoi2015]诸神眷顾的幻想乡(广义后缀自动机)
  9. 7.Linux 输入子系统分析
  10. 【Codeforces Round #455 (Div. 2) B】Segments