poj2718 Smallest Difference
来源:互联网 发布:画漫画软件sai 编辑:程序博客网 时间:2024/06/06 03:49
这一题,本来也挺简单的。只是用一个深度搜索做一个全排列,然后计算找出使两数差值最小的全排列。后来按照以前的方式写了一个全排列,交上去,告诉我TLE,这让在下很纠结啊。因为如果只是全排列的话,一共需要计算10!次,也就是说,不会超时。后来发现,自己以前写的算法有问题,在搜索的时候,会出现很多冗余的操作,使搜索的效率大大退化。后来更改了数据的处理方式,将算法复杂度降到了10!,然后提交,返回Accepted,不过运行时间大概是500+ms,效率感觉还是有点低了。想起了STL里面的全排列函数,next_permutation(),嗯,我还不会用,以后有空去查查。应该能把时间降到300ms吧。不过网上也有好多人用贪心做的,自己也能想个大概贪心思路,等有空试着写个贪心,看能不能A吧。下面上代码:
#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;int ans,hash[20],a[20],n;int dfs(int step){ int i,j,k,tmp,t1,t2; if(step==n) { t1=0; t2=0; for(i=0,k=1;i<n/2;i++,k*=10) t1+=k*a[i]; for(i=n/2,k=1;i<n;i++,k*=10) t2+=k*a[i]; if(t1-t2>0) t1=t1-t2; else t1=t2-t1; if(ans>t1) ans=t1; return 0; } for(i=step;i<n;i++) { if(n>3&&(step==n/2-1||step==n-1)&&a[i]==0) continue; if(n==3&&step==2&&a[i]==0) continue; swap(a[step],a[i]); dfs(step+1); swap(a[step],a[i]); }}int main(){ int i,j,k,T; scanf("%d ",&T); while(T--) { char ch; n=0; while((ch=getchar())!='\n') { if(ch==' ') continue; else a[n++]=ch-'0'; } ans=32767; dfs(0); printf("%d\n",ans); } return 0;}
0 0
- poj2718 Smallest Difference
- poj2718 Smallest Difference
- POJ2718---Smallest Difference
- [dfs]poj2718 Smallest Difference
- POJ2718-Smallest Difference
- Smallest Difference poj2718
- POJ2718 Smallest Difference
- POJ2718-Smallest Difference
- poj2718 Smallest Difference【贪心】
- POJ2718 Smallest Difference
- poj2718 Smallest Difference
- POJ2718 Smallest Difference 【贪心+枚举】
- POJ2718——Smallest Difference
- POJ2718-Smallest Difference-穷竭搜索
- POJ2718 Smallest Difference (暴力搜索+全排列)
- Smallest Difference(Poj2718)(枚举全排列next_Permutation)
- POJ2718——Smallest Difference(暴力瞎搞)
- 【POJ2718】Smallest Difference(枚举排列)
- lua require 中的路径 不能用斜杠(/) 和 点(.) 混用
- Node.js的事件
- C++静态成员函数
- 干货:机器学习领域的几种主要学习方式
- K线图的分类
- poj2718 Smallest Difference
- hdu 3004 The Chess【广独优先搜索】
- iOS开发笔记之三十一——UIButton的使用总结
- Crontab的格式
- 对进程地址空间的一点认识
- 手动部署web工程到TOMCAT的webapps下,报堆溢出或永久区异常错误解决办法
- 实现控制台的猜数字游戏。
- 黑马程序员——for循环
- 利用U盘制作虚拟软驱加载raid驱动