POJ2718 Smallest Difference
题目链接:
POJ2718 Smallest Difference
简单理解一下题目:
给定一些0-9中的数字,用这些数字组成两个数,求使得两个数之差最小的那种方案,输出两个数的差。
看一下输入:
1
0 1 2 4 6 7
输入的第一行表示有几个样例,接下来每一行就是一个样例,由于我们不知道每个样例有多少个数字,所以我用getchar()方法来输入。每输入一个字符就判断一下是不是换行符,如果是换行符就说明这个样例已经输入完毕,这里要注意的是,开头输入了一个样例总数之后需要用getchar()吞掉这个数字后面的换行符再开始输入样例。另外,存储的时候要记得把字符转换成数字,直接减去’0’字符即可
int cas;//样例总数
cin >> cas;
getchar();//吞掉cas后面的换行符
for (int i = 0; i < cas; i++) {
char c;
int index = 0;
while (true) {
c = getchar();
if (c == '\n')
break;
if(c!=' ')
a[index++] = c-'0';
}
solve(index);
}
解题思路:
solve()函数用于算出每个样例的结果,这题可以直接用暴力搜索,数组中的数字平均分成两份,搜索所有的情况,记录最小差值,这里用next_permutation()函数进行全排列,然后数组前半部分作为一个数字,后半部分作为一个数字。
AC代码:
#include<iostream>
#include<algorithm>
using namespace std;
char a[12];
void solve(int ind) {
if (ind == 2) {
cout << abs(a[0] - a[1]) << endl;
return;
}
int res = 1e9;
do {
if (a[0] == 0 || a[ind / 2] == 0) {
continue;
}
int front = 0;//记录前半部分数字
int back = 0;//记录后半部分数字
for (int i = 0; i < ind / 2; i++) {
front *= 10;
front += a[i];
}
for (int i = ind / 2; i < ind; i++) {
back *= 10;
back += a[i];
}
if (abs(front - back) < res)
res = abs(front - back);
} while (next_permutation(a, a + ind));
cout << res << endl;
return;
}
int main() {
int cas;//样例总数
cin >> cas;
getchar();//吞掉cas后面的换行符
for (int i = 0; i < cas; i++) {
char c;
int index = 0;
while (true) {
c = getchar();
if (c == '\n')
break;
if(c!=' ')
a[index++] = c-'0';
}
solve(index);
}
return 0;
}
/*
1
0 1 2 4 6 7
*/