[挑战程序设计竞赛] POJ 2718 - Smallest Difference
来源:互联网 发布:儿童图书软件 编辑:程序博客网 时间:2024/06/01 07:39
题意:
给定0~9之间的一些不重复的数字,把这些数字任意组合成两部分,求两部分数字的差的绝对值的最小值。(注意不能有前导0~)
仔细想了一下发现:
当给定数字个数为奇数时,两部分的个数应该是差一位的。
当给定数字个数为偶数时,两部分的个数应该是相等的。
用DFS做了一下,结果提交后TLE了,然后想了一下,发现输入的数字的个数为10的时候,结果只有一种~
于是特判数字个数为10的时候,直接输出结果。。这题就被水过了。。
#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int a[15], cnt, ans, vis[11], b[15];int abs(int x){ if(x < 0) { return -x; } return x;}void dfs(int deep){ if(deep == cnt) { int left = 0; int mid = cnt / 2; for(int j = 0; j < mid; j++) { if(b[0] == 0 && mid > 1) { return ; } left = left * 10 + b[j]; } int right = 0; for(int j = mid; j < cnt; j++) { if(b[mid] == 0 && cnt > mid + 1) { return ; } right = right * 10 + b[j]; } ans = min(ans, abs(left - right)); } else { for(int i = 0; i < cnt; i++) { if(!vis[i]) { b[deep] = a[i]; vis[i] = 1; dfs(deep + 1); vis[i] = 0; } } }}int main(){ int T; char ch; while(~scanf("%d", &T)) { getchar(); for(int i = 0; i < T; i++) { ans = 1000000000; memset(vis, 0, sizeof(vis)); cnt = 0; while((ch = getchar()) != '\n') { if(ch >= '0' && ch <= '9') a[cnt++] = ch - '0'; } if(cnt == 10) { printf("247\n"); continue; } dfs(0); printf("%d\n", ans); } }}
0 0
- [挑战程序设计竞赛] POJ 2718 - Smallest Difference
- POJ 2718-Smallest Difference [dfs] 《挑战程序设计竞赛》2.1
- ACM 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
- POJ 2718 Smallest Difference
- POJ 2718 Smallest Difference
- POJ 2718 Smallest Difference
- Smallest Difference(POJ-2718)
- POJ 2718 Smallest Difference
- POJ-2718 Smallest Difference
- poj-2718 Smallest Difference
- poj 2718 Smallest Difference
- 基于web服务的文件共享平台pydio搭建教程
- nodejs上传功能实现
- IOS后台运行
- 多线程编程
- elasticsearch数据备份与还原恢复
- [挑战程序设计竞赛] POJ 2718 - Smallest Difference
- w3m 设置用户名密码自动登录
- UVa 12333 - Revenge of Fibonacci(字典树+高精度压位)
- domino新注册用户、修改密码生效慢的变通解决办法
- Linux 网络编程之ioctl函数
- 2014-11-IOS 获取最新设备型号方法
- SpringMVC总结(五)上传
- Swift learn 7
- 人见人爱A+B