Codeforces Round #604 (Div. 2) D. Beautiful Sequence(构造/贪心)

题目链接:https://codeforces.com/contest/1265/problem/D

题意

用 $a$ 个 $0$,$b$ 个 $1$,$c$ 个 $2$,$d$ 个 $3$ 构造一个数列,使得所有相邻的两个数相差为 $1$ 。

题解

枚举数列的首部,假设前一个数的值为 $last$,当前数优先使用 $last - 1$(因为之后就没机会了),次优先使用 $last + 1$,然后更新 $last$ 的值。若可以依此构造出一个长为 $a + b + c + d$ 的数列,则有解。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    map<int, int> mp;
    int total = 0;
    for (int i = 0; i < 4; i++)
        cin >> mp[i], total += mp[i];
    for (int st = 0; st < 4; st++) {
        if (mp[st]) {
            auto cnt = mp;
            vector<int> res;
            int last = st;
            res.push_back(last);
            cnt[last]--;
            for (int i = 0; i < total - 1; i++) {
                if (cnt[last - 1]) {
                    res.push_back(last - 1);
                    cnt[last - 1]--;
                    last--;
                } else if (cnt[last + 1]) {
                    res.push_back(last + 1);
                    cnt[last + 1]--;
                    last++;
                } else break;
            }
            if (res.size() == total) {
                cout << "YES" << "\n";
                for (int i = 0; i < res.size(); i++)
                    cout << res[i] << ' ';
                return 0;
            }
        }
    }
    cout << "NO" << "\n";
}

 

posted @ 2020-06-23 21:25  Kanoon  阅读(147)  评论(0)    收藏  举报