POJ 2718 Smallest Difference(暴力枚举)
来源:互联网 发布:盘搜搜源码 编辑:程序博客网 时间:2024/04/30 16:14
题意:一行中有不超过十个数而且不会重复而且是递增给出的。然后你把他们分成两份组合起来成一个数字,让这两个数字相差最小。输出最小的差值。不能有前导零(除非这个数本来就是0)
解法:很明显,如果是奇数的话,我们直接就可以贪心得到答案了。
偶数的话,还要分出为2的情况,这样的话就会出现可能有0的情况。答案直接就是后一个减去前一个。
然后枚举相邻的两个数a,b(a<b),当作两个起点,然后剩下序列里面小的数字扔到b里面,大的数字扔到a里面,管他什么贪心,直接暴力枚举。
一开始傻逼了,我打算先判断一下这个序列里面相邻两个数最小是多少,这样在偶数的情况下可以用到。然后枚举两个起点的时候还需要判断不能为0,遇到0 1 2的情况还好,遇到0 1 3就完了。想了好久,最后打断点跑oj数据终于找到错误。。。
代码如下:
#include<iostream>#include<stdio.h>#include<algorithm>#include<stdlib.h>using namespace std;const int INF = 0x7fffffff;int Min = 0x7fffffff, tmp = 0x7fffffff;int lenb = 1, lenc = 1;int n, k1, k2;int a[15], b[15], c[15];void mycount() {int t1 = 0, t2 = 0;for(int i = 0; i < lenb; i++) {t1 = t1 * 10 + b[i];t2 = t2 * 10 + c[i];}//cout << t1 << " " << t2 << endl;if(Min > abs(t2 - t1)) {Min = abs(t2 - t1);k1 = t1;k2 = t2;}}int main() {int T;char ch;cin >> T;getchar();while(T--) {Min = INF;for(n = 0; (ch = getchar()); ) {if(ch >= '0' && ch <= '9')a[n++] = ch - '0';else if(ch == '\n')break;}//sort(a, a + n);if(n == 2) {Min = a[1] - a[0];k1 = a[1];k2 = a[0];}else if(n % 2 == 0) {//tmp = INF;//for(int i = 0; i < n - 1; i++)//tmp = min(tmp, a[i + 1] - a[i]);//if(tmp == INF)//while(1);for(int i = 0; i < n - 1; i++) {if(a[i] != 0) {lenb = lenc = 0;b[lenb++] = a[i];c[lenc++] = a[i + 1];for(int j = 0; j < n; j++) {if(j != i && j != i + 1) {if(lenc < n / 2)c[lenc++] = a[j];elseb[lenb++] = a[j];}}mycount();while(next_permutation(b + 1, b + lenb)) {mycount();while(next_permutation(c + 1, c + lenc)) {mycount();}mycount();}mycount();}}//if(Min == INF)//Min = 0; } else {lenb = lenc = 0;int t1 = 0, t2 = 0, s = 1;t1 = a[0];t2 = a[n - 1];if(a[0] == 0) {t1 = a[1] * 10 + a[0];s = 2;}for(int i = s; i < (n + 1) / 2; i++)t1 = t1 * 10 + a[i];for(int i = n - 2; i >= (n + 1) / 2; i--) t2 = t2 * 10 + a[i];Min = abs(t1 - t2);k1 = t1;k2 = t2; }cout << Min << endl;//cout << k1 << " " << k2 << endl;}return 0;}
阅读全文
0 0
- Smallest Difference (poj 2718 暴力枚举)
- poj 2718 Smallest Difference (STL 暴力枚举)
- POJ:2718 Smallest Difference(暴力枚举)
- POJ 2718 Smallest Difference(暴力枚举)
- POJ 2718 Smallest Difference(贪心 or next_permutation()暴力枚举)
- POJ 2718 Smallest Difference(贪心 or next_permutation暴力枚举)
- POJ-----2718---Smallest Difference---暴力
- POJ 2718 Smallest Difference 枚举
- poj 2718 Smallest Difference(暴力搜索+STL+DFS)
- POJ 2718 Smallest Difference(暴力,全排列,next_permutation)
- POJ 2718 Smallest Difference
- poj 2718 Smallest Difference
- POJ-2718-Smallest Difference
- poj 2718 Smallest Difference
- poj 2718 Smallest Difference
- POJ 2718-Smallest Difference
- POJ 2718 Smallest Difference
- POJ 2718 Smallest Difference
- epoll TcpMultiplexor笔记
- 安装Kibana
- DOM节点类型
- 最小生成树Prim算法模板
- GraphicsMagick在mac-os下货Linux下安装及使用
- POJ 2718 Smallest Difference(暴力枚举)
- 剑指offer面试题-二叉树的前序中序后序遍历
- 微商想要做的长远有价值 怎样避免赚差价误区
- 算法系列——Subsets II
- Linux权限管理
- 英文语音语调的学习
- 安装Logstash
- HDU 1021找规律水题
- Literature Lesson CodeForces