Saturday, January 4, 2020

POJ.2718 Smallest Difference

Problem:
http://poj.org/problem?id=2718

Idea:
Using std.algortihm next_permutation to generate all possible permutations, and only need to check the 2 numbers that you get when splitting the seq in the middle. Also watch out 0 included 2 number cases.

Source:
 int main()  
 {  
      int t;  
      scanf("%d\n", &t);  
      for (int i = 0; i < t; i++) {  
           int ans = 123456789;  
           vector<int> a;  
           char cc;  
           while (cc = getchar()) {  
                if (cc == '\n') break;  
                if (cc >= '0' && cc <= '9') a.push_back((int)(cc - '0'));  
           }  
           int n = a.size();  
           int m = n / 2;  
           sort(a.begin(), a.end());  
           do {                 
                if ( (a[0] == 0 && m-1 > 0) || (a[m] == 0 && m < n-1) ) continue;  
                int num1 = 0;  
                for (int j = 0; j < m; j++) {  
                     num1 = 10 * num1 + a[j];  
                }  
                int num2 = 0;  
                for (int j = m; j < n; j++) {  
                     num2 = 10 * num2 + a[j];  
                }  
                ans = min(ans, abs(num1 - num2));  
           } while (next_permutation(a.begin(), a.end()));  
           cout << ans << endl;  
      }  
      return 0;  
 }  

No comments:

Post a Comment