POJ - 2718 Smallest Difference(全排列)
2024-09-07 04:38:48
题意:将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;
}
最新文章
- Java多线程整理(li)
- Javascript中prototype属性详解
- Linux下Java安装与配置
- codeforces 721B B. Passwords(贪心)
- 【Todo】InnoDB、MyISAM、数据库引擎
- phonegap WebApp
- java中的synchronized关键字
- 探究Android中Listview显示错乱问题
- 【RecyclerView与Glide】实现一个Android电子书阅读APP
- UTF-8 UTF-16 UTF-32 最根本的区别?
- 剑指Offer_编程题_23
- 关于Rabbitmq的routingkey的作用
- 小程序上传wx.uploadFile - 小程序请假
- View体系之属性动画
- CH2401 送礼物(算竞进阶习题)
- elasticsearch自动按天创建索引脚本
- Orleans学习总结(二)--创建工程
- <;Web Crawler>;<;Java>;<;thread-safe queue>;
- Maven上传构建到私服
- Python之路(第八篇)Python内置函数、zip()、max()、min()