POJ2718 Posted on 2017-03-30 | In Competitive Programming , POJ Smallest DifferenceSolution sketch基本上就是全排列後,中間切一半求差。 小心 leading zero 和 only zero 的 case。 AC code1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556#include <algorithm>#include <climits>#include <cstdio>#include <cstdlib>#include <cstring>#include <vector>using namespace std;int main(){ int ncase; char str[100]; fgets(str, 100, stdin); sscanf(str, "%d", &ncase); while (ncase--) { vector<int> inp; char str[100]; fgets(str, 100, stdin); char *num = strtok(str, " "); while (num != NULL) { inp.push_back(atoi(num)); num = strtok(NULL, " "); } int sz = inp.size(); int res = INT_MAX; do { bool error = false; int r = 0, l = 0; for (int i = 0; i < sz / 2; i++) { if (sz > 1 && i == 0 && inp[i] == 0) error = true; r *= 10; r += inp[i]; } for (int i = sz / 2; i < sz; i++) { if (sz - sz / 2 > 1 && i == sz / 2 && inp[i] == 0) error = true; l *= 10; l += inp[i]; } if (error == false) { res = min(res, abs(r - l)); } } while (next_permutation(inp.begin(), inp.end())); printf("%d\n", res); } return 0;} AC code想太多了,竟然先想說對於所有的分堆可能,窮舉。 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182#include <algorithm>#include <climits>#include <cstdio>#include <cstdlib>#include <cstring>#include <vector>using namespace std;int main(){ int ncase; char str[100]; fgets(str, 100, stdin); sscanf(str, "%d", &ncase); while (ncase--) { vector<int> inp; char str[100]; fgets(str, 100, stdin); char *num = strtok(str, " "); while (num != NULL) { inp.push_back(atoi(num)); num = strtok(NULL, " "); } int sz = inp.size(); int res = INT_MAX; for (int i = 0; i < (1 << sz); i++) { if (__builtin_popcount(i) == (sz / 2)) { vector<int> left, right; for (int j = 0; j < sz; j++) { if ((i >> j) & 1) right.push_back(inp[j]); else left.push_back(inp[j]); } vector<int> r, l; if (sz / 2 == 1 && right[0] == 0) { r.push_back(0); } do { if (right[0] == 0) continue; int rnum = 0; for (int j = 0; j < (int)right.size(); j++) { rnum *= 10; rnum += right[j]; } r.push_back(rnum); } while (next_permutation(right.begin(), right.end())); if ((sz - sz / 2) == 1 && left[0] == 0) { l.push_back(0); } do { if (left[0] == 0) continue; int lnum = 0; for (int j = 0; j < (int)left.size(); j++) { lnum *= 10; lnum += left[j]; } l.push_back(lnum); } while (next_permutation(left.begin(), left.end())); for (int j = 0; j < (int)l.size(); j++) { for (int k = 0; k < (int)r.size(); k++) { res = min(res, abs(l[j] - r[k])); } } } } printf("%d\n", res); } return 0;}