• 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 }
  • 相关阅读:
    生产者-消费者模型-线程安全队列Queue
    多线程简单案例
    cloudstack 用admin 账号创建虚拟机只是提示insufficient resource
    什么是工厂函数?Python 中工厂函数怎么理解?(转)
    rsync + mysql + gzip + --single-transaction
    Python中获取异常(try Exception)信息
    ansible copy 模块 changed false 没有变化
    _mysql.c:29:20: error: Python.h: No such file or directory
    常用网址
    Android 中常见控件的介绍和使用
  • 原文地址:https://www.cnblogs.com/fzl194/p/8823636.html
Copyright © 2020-2023  润新知