poj2718 穷举

 

 

POJ 2718 Smallest Difference

将一个数切一刀拆成两个数,两个数每一位数字的顺序都可改变,但是不能有前导0。求这两个数之差的最小值。

我使用了搜索并且避免了递归,自认为是比较好的算法。

一开始我想到的是枚举,并且很快给出了实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#ifndef ONLINE_JUDGE
#pragma warning(disable : 4996)
#endif
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
///////////////////////////SubMain//////////////////////////////////
int main( int argc, char *argv[])
{
#ifndef ONLINE_JUDGE
    freopen ( "in.txt" , "r" , stdin);
    freopen ( "out.txt" , "w" , stdout);
#endif
    int n;
    cin >> n;
    cin.ignore();
    while (n--)
    {
        string all;
        getline(cin, all);
        all.erase( remove (all.begin(), all.end(), ' ' ), all.end());
        int result = 0x3F3F3F3F;
        int cut = all.size() / 2;
        do
        {
            string s1 = all.substr(0, cut);
            string s2 = all.substr(cut);
            if ((s1[0] == '0' && s1.size() > 1) ||
                (s2[0] == '0' && s2.size() > 1)
                )
            {
                continue ;
            }
            int n1 = atoi (s1.c_str());
            int n2 = atoi (s2.c_str());
            int dif = abs (n1 - n2);
            if (dif < result)
            {
                result = dif;
            }
        } while (next_permutation(all.begin(), all.end()));
       
        cout << result << endl;
    }
#ifndef ONLINE_JUDGE
    fclose (stdin);
    fclose (stdout);
    system ( "out.txt" );
#endif
    return 0;
}
///////////////////////////End Sub//////////////////////////////////

没料到TLE,后来想了想,这里的复杂度是O((length!)n),当length = 10 的时候内层最高达到了3628800 次循环,而用例则可能是很多的。

要优化得下点功夫,起先想到改用模拟的方法,分奇偶讨论,可是这道题目是放在2.1 最基础的“穷竭搜索” 穷竭搜索这节里,目的是训练搜索算法。

于是继续走搜索的路线,上面的程序之所以慢,是因为重复计算。比如第一个字串为12,第二个字串为34这种情况和第一个字串为34,第二个字串为12这种情况被视作不同的情况。这是应当被优化的第一个点。

第二个点是string类型的全排操作比较费时,可以用位运算优化。

我看到有些人用dfs递归,感觉很别扭,代码一不好理解,二浪费栈。

我使用了我最喜欢的玩具bitset:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#ifndef ONLINE_JUDGE
#pragma warning(disable : 4996)
#endif
#include <iostream>
#include <string>
#include <algorithm>
#include <bitset>
using namespace std;
///////////////////////////SubMain//////////////////////////////////
int main( int argc, char *argv[])
{
#ifndef ONLINE_JUDGE
    freopen ( "in.txt" , "r" , stdin);
    freopen ( "out.txt" , "w" , stdout);
#endif
    int n;
    cin >> n;
    cin.ignore();
    while (n--)
    {
        string all;
        getline(cin, all);
        all.erase( remove (all.begin(), all.end(), ' ' ), all.end());
        int length = all.size();
        int cut = length / 2;
        int permute = 1 << length;
        int result = 0x3F3F3F3F;
        do
        {
            bitset<10> used = static_cast <bitset<10>>(permute);
            string s1, s2;
            for ( int i = 0; i < length; ++i)
            {
                if (used[i])
                {
                    s1 += all[i];
                }
                else
                {
                    s2 += all[i];
                }
            }
            if (s1.size() != cut)
            {
                continue ;
            }
            if (s1[0] == '0' && s1.size() > 1)
            {
                continue ;
            }
            // s1 s2 已经被切割出来了
            // 穷举它们
            do
            {
                int n1 = atoi (s1.c_str());
                do
                {
                    if (s2[0] == '0' && s2.size() > 1)
                    {
                        continue ;
                    }
                    int n2 = atoi (s2.c_str());
                    int dif = abs (n1 - n2);
                    //cout << s1 << ' ' << s2 << " dif " << dif << " result: " << result << endl;
                    if (dif < result)
                    {
                        result = dif;
                    }
                } while (next_permutation(s2.begin(), s2.end()));
            } while (next_permutation(s1.begin(), s1.end()));
        } while (--permute);
        cout << result << endl;
    }
#ifndef ONLINE_JUDGE
    fclose (stdin);
    fclose (stdout);
    system ( "out.txt" );
#endif
    return 0;
}
///////////////////////////End Sub//////////////////////////////////

 

转自:http://www.hankcs.com/program/poj-2718-smallest-difference-challenge-programming-contest-2nd-edition-exercises-answers.html

 

很好的算法和思路!

对bitset不懂的看这里:http://blog.163.com/lixiangqiu_9202/blog/static/53575037201251121331412/

其中getline(cin,str)在VC6.0中下一行还会要去读取字符,这是VC6的一个BUG。

还有C++的remove函数,其实是将字符替换成字符串后续的字符。并不是移除,因此要配合string类的erase函数,释放后续空间,才是删除。

http://zhidao.baidu.com/link?url=Oig1CxkpjjgTYgWKGE8DOV4mqt4PH1l_AwbZIhiIf8mic8WCv7byEgRKFKlYoNEieunDIVYrruHoryQgLtQD2q

 

用1<<length初始化bitset,每次循环减一,相当于枚举了给出的数的1或0的所有情况。对于每一种情况每次取出一种s1的排列,在取出一种s2的排列,避免了重复。

600多ms过。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值