洛谷 P1489 猫狗大战 题解

· · 题解

本题解并不正经,请谨慎食用

老规矩,先放AC代码:

#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
using namespace std;

const int N = 2e2 + 10;
int M = 1e5 + 1e4,n,a[N],sum,c = 1e9,ans1,ans2;

signed main()
{
    ios::sync_with_stdio(0);
    cin >> n;
    for(int i = 1;i <= n;i ++) cin >> a[i],sum += a[i];
    int cnt1 = n / 2;
    for(int i = 1;i <= M;i ++)
    {
        random_shuffle(a + 1,a + n + 1);
        int x = 0;
        for(int j = 1;j <= cnt1;j ++) x += a[j];
        int y = sum - x;
        if (abs(y - x) < c) c = abs(y - x),ans1 = y,ans2 = x;
        if (abs(x + a[cnt1 + 1] - y - a[cnt1 + 1]) < c) c = abs(x + a[cnt1 + 1] - y - a[cnt1 + 1]),ans1 = x,ans2 = y;
    }
    cout << min(ans1,ans2) << ' ' << max(ans1,ans2) << endl;
    return 0;
}

看到这里,有些同学就会有疑问了:“这什么玩意儿啊?什么算法都没有!”

这里,就要讲到骗分大招:随机化!!!

这道题一看就是一道DP,但是DP非常难想,连我也没有想出来。

这题的数据范围很小,n <= 200!! 而且,这道题没有复杂的情况,仅仅只有第一队和第二队

于是,我们就可以每次随机打乱数组,前n / 2个是第一队,后n / 2个是后一队,每次计算差值和一队二队,最后只要输出差值最小的就可以了!

这里重点介绍一个函数:random_shuffle(begin,end),作用是把begin到end的数组全部打乱。(类似sort)

这里计算过,最大随机次数大约1e5,我就不信还出不了1次!