[BZOJ3523][[Poi2014]Bricks][贪心+优先队列]

来源:互联网 发布:sql 2张表合并 编辑:程序博客网 时间:2024/05/23 19:19

[BZOJ3523][[Poi2014]Bricks][贪心+优先队列]

题目大意:

给你每种颜色的砖块数量,相同颜色的砖块不能放在一起,两头颜色已经确定,构造一种方案

思路:

直接贪心,每次选择砖块数量最多的颜色,如果颜色相同优先考虑最后一块砖块的颜色(显然为了防止和最后一块颜色相同,要把这些砖块提前放掉。)

维护数量最多的颜色可以用优先队列,每次取出队首,如果颜色和前一块砖块颜色一样就再取队首,然后把第一次取出来的放回去。

第一块和最后一块颜色可能相同,减要分别减一次再扔到队列里……

代码:

WA和RE了好多次……

#include <cstdio>#include <queue>using namespace std;const int Maxn = 1000010;inline char get(void) {    static char buf[1000000], *p1 = buf, *p2 = buf;    if (p1 == p2) {        p2 = (p1 = buf) + fread(buf, 1, 1000000, stdin);        if (p1 == p2) return EOF;    }    return *p1++;}inline void read(int &x) {    x = 0; static char c; bool minus = false;    for (; !(c >= '0' && c <= '9'); c = get()) if (c == '-') minus = true;    for (; c >= '0' && c <= '9'; x = x * 10 + c - '0', c = get()); if (minus) x = -x;}int s, e, n, m, ans[Maxn];struct Abcd {    int c, n;    friend bool operator < (const Abcd &a, const Abcd &b) {        if (a.n == b.n) return !(a.c == e);        else return a.n < b.n;    }} tmp, tmp2;priority_queue<Abcd> qu;int main(void) {    //freopen("in.txt", "r", stdin);    //freopen("out.txt", "w", stdout);    read(n), read(s), read(e);     for (int i = 1; i <= n; i++) {        read(tmp.n);        tmp.c = i;        if (tmp.c == s) tmp.n--;        if (tmp.c == e) tmp.n--;        if (tmp.n < 0) return puts("0"), 0;        m += tmp.n;        if (tmp.n) qu.push(tmp);    }    ans[0] = s, ans[m + 1] = e;    for (int i = 1; i <= m; i++) {        tmp = qu.top(); qu.pop();        if (tmp.c != ans[i - 1]) {            ans[i] = tmp.c;            tmp.n--;            if (tmp.n) qu.push(tmp);        }        else {            if (qu.empty()) return puts("0"), 0;            tmp2 = qu.top(); qu.pop();            ans[i] = tmp2.c;            tmp2.n--;            if (tmp2.n) qu.push(tmp2);            qu.push(tmp);        }    }    if (ans[m] == ans[m + 1]) return puts("0"), 0;    for (int i = 0; i <= m + 1; i++) printf("%d ", ans[i]);    return 0;}

完。

By g1n0st

1 0
原创粉丝点击