POJ-2718 Smallest Difference---DFS

题目链接:

https://vjudge.net/problem/POJ-2718

题目大意:

有一列数,对其任意分成两组,每组按一定顺序可以组成一个数。问得到的两个数的差最小是多少。

思路:

直接dfs构造就行,注意不能有前导0。而且有数据需要特判

只有一个数字的时候需要特判,还有只有两个数字的时候也需要特判,这是因为如果含有0和其他的数字,由于在构造中不允许前导0的出现,所以如果有这种情况的话更新不了minans,所以只有两个数字的时候也需要特判

 1 #include<iostream>
 2 #include<vector>
 3 #include<queue>
 4 #include<algorithm>
 5 #include<cstring>
 6 #include<cstdio>
 7 #include<set>
 8 #include<map>
 9 #include<cmath>
10 #include<sstream>
11 using namespace std;
12 typedef pair<int, int> Pair;
13 typedef long long ll;
14 const int INF = 0x3f3f3f3f;
15 int T, n, m, minans;
16 const int maxn = 1e5 + 10;
17 int dir[4][2] = {1,0,0,1,-1,0,0,-1};
18 int a[15];
19 bool v[15];
20 void dfs(int num, int d)
21 {
22     if(d == n / 2)//递归出口
23     {
24         int b[10], tot = 0;
25         for(int i = 0; i < n; i++)
26             if(!v[i])b[tot++] = a[i];
27         sort(b, b + tot);
28         do
29         {
30             if(!b[0])continue;
31             int x = 0;
32             for(int i = 0; i < tot; i++)x = x * 10 + b[i];
33             minans = min(minans, abs(num - x));
34         }while(next_permutation(b, b + tot));
35         return;
36     }
37     for(int i = 0; i < n; i++)
38     {
39         if(!v[i])
40         {
41             v[i] = 1;
42             dfs(num * 10 + a[i], d + 1);
43             v[i] = 0;
44         }
45     }
46 }
47 int main()
48 {
49     cin >> T;
50     getchar();
51     while(T--)
52     {
53         string s;
54         n = 0;
55         minans = INF;
56         getline(cin, s);
57         stringstream ss(s);
58         while(ss >> a[n++]);
59         n--;//此处需要自减一,因为n在ss流完的时候又加了一
60         if(n == 1)//特例特判
61         {
62             cout<<abs(a[0])<<endl;
63         }
64         else if(n == 2)
65         {
66             cout<<(abs(a[0] - a[1]))<<endl;
67         }
68         else 
69         {
70             for(int i = 0; i < n; i++)
71             {
72                 memset(v, 0, sizeof(v));
73                 if(!a[i])continue;
74                 v[i] = 1;
75                 dfs(a[i], 1);
76             }
77             cout<<minans<<endl;
78         }
79     }
80     return 0;
81 }

 

posted @ 2018-04-13 20:32  _努力努力再努力x  阅读(129)  评论(0编辑  收藏  举报