标签:out input 偶数 add targe wap end while i++
题目:POJ 2718
思路:
分为奇数和偶数两种情况进行处理,输入个数为奇数的时候,无须穷举,最小差是一定的,如0 1 2 3 4,最小差为102 - 43。
输入个数为偶数的时候,用next_permutation穷举。
没有AC……
1 #include <iostream> 2 #include <algorithm> 3 #include <iostream> 4 #include <stdio.h> 5 #include <string.h> 6 7 using namespace std; 8 9 int n; 10 int input[28]; 11 char num[128]; 12 13 long long pow10(int n) 14 { 15 long long ret = 1; 16 for (int i = 0 ;i < n; i++) 17 { 18 ret *= 10; 19 } 20 return ret; 21 } 22 23 int getNumber(int * addr, int count, bool isMin) { 24 int res = 0; 25 if (isMin) { 26 if (addr[0] == 0) { 27 swap(addr[0], addr[1]); 28 } 29 for (int i = count - 1; i >= 0; i--) { 30 res += *(addr + (count - 1 - i)) * pow10(i); 31 } 32 } 33 else { 34 for (int i = 0; i < count; i++) { 35 res += *(addr + i) * pow10(i); 36 } 37 } 38 return res; 39 } 40 41 int main() { 42 cin >> n; 43 cin.ignore(); 44 int lc; //left count 45 int rc; //right count 46 47 int f; 48 int diff; 49 for (int i = 0; i < n; i++) { 50 int count = 0; 51 diff = 0x3f3f3f3f; 52 gets(num); 53 for (int i = 0; i < strlen(num); i++) 54 { 55 if (num[i] >= ‘0‘ && num[i] <= ‘9‘) input[count++] = num[i] - ‘0‘; 56 } 57 58 rc = count >> 1; //left count 59 lc = count - rc; //right count 60 if (count % 2 == 0) { 61 int tempCount = 0; 62 do { 63 diff = min(diff, abs(getNumber(input, lc, 1) - getNumber(input + lc, rc, 1))); 64 } while (next_permutation(input, input + count)); 65 } 66 else { 67 diff = min(diff, abs(getNumber(input, lc, 1) - getNumber(input + lc, rc, 0))); 68 } 69 cout << diff << endl; 70 } 71 return 0; 72 }
总结:
gets(num); for (int i = 0; i < strlen(num); i++) { if (num[i] >= ‘0‘ && num[i] <= ‘9‘) input[count++] = num[i] - ‘0‘; }
POJ 2718 Smallest Difference 未AC 《挑战程序设计竞赛》
标签:out input 偶数 add targe wap end while i++
原文地址:http://www.cnblogs.com/carolunar/p/6362361.html