题意:将n个数字分成两组,两组分别组成一个数字,问两个数字的最小差值。要求,当组内数字个数多于1个时,组成的数字不允许有前导0。(2<=n<=10,每个数字范围是0~9)

分析:

1、枚举n个数字的全排列。

2、当两组数字个数相同或只差1时组成的两个数字才可能出现最小差值。

3、0~cnt/2 - 1为前半组数字,cnt/2~cnt-1为后半组数字。

4、注意getchar()的位置。

#pragma comment(linker, "/STACK:102400000, 102400000")
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cctype>
#include<cmath>
#include<iostream>
#include<sstream>
#include<iterator>
#include<algorithm>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<deque>
#include<queue>
#include<list>
#define Min(a, b) ((a < b) ? a : b)
#define Max(a, b) ((a < b) ? b : a)
const double eps = 1e-8;
inline int dcmp(double a, double b){
if(fabs(a - b) < eps) return 0;
return a > b ? 1 : -1;
}
typedef long long LL;
typedef unsigned long long ULL;
const int INT_INF = 0x3f3f3f3f;
const int INT_M_INF = 0x7f7f7f7f;
const LL LL_INF = 0x3f3f3f3f3f3f3f3f;
const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
const int MOD = 1e9 + 7;
const double pi = acos(-1.0);
const int MAXN = 10 + 10;
const int MAXT = 10000 + 10;
using namespace std;
int a[MAXN];
string s;
int cnt;
bool judge(){
if(a[0] == 0 && cnt / 2 - 0 > 1) return false;//前半组数字个数大于1
if(a[cnt / 2] == 0 && cnt - cnt / 2 > 1) return false;//后半组数字个数大于1
return true;
}
int main(){
int T;
scanf("%d", &T);
getchar();
while(T--){
getline(cin, s);
stringstream ss(s);
int x;
cnt = 0;
while(ss >> x){
a[cnt++] = x;
}
sort(a, a + cnt);
int ans = INT_INF;
do{
int sum1 = 0, sum2 = 0;
if(!judge()) continue;
for(int i = 0; i < cnt / 2; ++i){
sum1 = sum1 * 10 + a[i];
}
for(int i = cnt / 2; i < cnt; ++i){
sum2 = sum2 * 10 + a[i];
}
ans = Min(ans, abs(sum1 - sum2));
}while(next_permutation(a, a + cnt));
printf("%d\n", ans);
}
return 0;
}

  

最新文章

  1. Java多线程整理(li)
  2. Javascript中prototype属性详解
  3. Linux下Java安装与配置
  4. codeforces 721B B. Passwords(贪心)
  5. 【Todo】InnoDB、MyISAM、数据库引擎
  6. phonegap WebApp
  7. java中的synchronized关键字
  8. 探究Android中Listview显示错乱问题
  9. 【RecyclerView与Glide】实现一个Android电子书阅读APP
  10. UTF-8 UTF-16 UTF-32 最根本的区别?
  11. 剑指Offer_编程题_23
  12. 关于Rabbitmq的routingkey的作用
  13. 小程序上传wx.uploadFile - 小程序请假
  14. View体系之属性动画
  15. CH2401 送礼物(算竞进阶习题)
  16. elasticsearch自动按天创建索引脚本
  17. Orleans学习总结(二)--创建工程
  18. &lt;Web Crawler&gt;&lt;Java&gt;&lt;thread-safe queue&gt;
  19. Maven上传构建到私服
  20. Python之路(第八篇)Python内置函数、zip()、max()、min()

热门文章

  1. Python测试进阶——(2)配置PyCharm远程调试环境
  2. 弱点扫描-openvas初始化
  3. java文件的上传
  4. java核心-多线程(9)- ThreadLocal类
  5. java项目构建工具Maven
  6. 【学CG系列】web之审查元素
  7. Linux netfliter 架构
  8. SQL语句中为什么要用 where 1=1
  9. 09.swoole学习笔记--创建进程
  10. TensorFlow2 Part3:动态模型建立与训练