标签: 贪心

  • 十二省联考2019 春节(清明)十二响

    把你骨灰都给你扬了!

    真是送分题…可惜因为心态原因考场上想出来正解了都没敢写..

    首先考虑链的情况怎么做?

    既然根不是链的端点,那么这条链一定分为两部分,把两部分的所有权值扔堆里,每次各拿出来两部分的最大值进行配对,然后扔到结果里。

    最后加起来即可。

    推广到树上呢?

    很自然的想到写个DFS,这个DFS返回一个堆,表示这棵子树的答案。

    然后对于一个点把他的子节点的堆拿出来每次取出所有的最大值合并

    这样也是正确的,可惜时间复杂度和空间复杂度都可以被卡到$O(n^2)$。

    怎么优化呢?考虑到一个到子树内叶子节点最远距离为x的点,堆里只会有x个取值。

    所以我们可以长链剖分。

    对于一个点,我们优先递归它的深子节点,然后把其他的子节点的答案合并到这个深子节点的堆上。

    具体实现就是对于一条长链顶,我们新建一个堆,然后这条长链都使用这一个堆。

    当从长链顶返回时,合并完答案后,删除这个堆即可。

    时间复杂度为所有长链长度之和乘上堆的复杂度,即$O(nlogn)$。

    #include <assert.h>
    #include <iostream>
    #include <numeric>
    #include <queue>
    #include <set>
    using int_t = long long int;
    using std::cin;
    using std::cout;
    using std::endl;
    
    using heap_t = std::multiset<int_t, std::greater<int_t>>;
    
    const int_t LARGE = 2e5;
    int_t maxChd[LARGE + 1], depth[LARGE + 1], maxDepth[LARGE + 1];
    int_t vals[LARGE + 1];
    int_t n;
    std::vector<int_t> graph[LARGE + 1];
    
    void DFS1(int_t vtx) {
        maxDepth[vtx] = depth[vtx];
        for (int_t to : graph[vtx]) {
            depth[to] = depth[vtx] + 1;
            DFS1(to);
            maxDepth[vtx] = std::max(maxDepth[vtx], maxDepth[to]);
        }
        for (int_t to : graph[vtx]) {
            if (maxDepth[to] > maxDepth[maxChd[vtx]]) {
                maxChd[vtx] = to;
            }
        }
        if (maxChd[vtx] == vtx) maxChd[vtx] = 0;
    }
    void DFS2(int_t vtx, heap_t* heap) {
        //先递归重子节点
        if (maxChd[vtx]) DFS2(maxChd[vtx], heap);
        //递归非重子节点
        std::vector<heap_t*> heaps;
        for (int_t to : graph[vtx]) {
            if (to != maxChd[vtx]) {
                auto next = new heap_t;
                DFS2(to, next);
                heaps.push_back(next);
            }
        }
        std::vector<int_t> result;
        //合并答案
        while (true) {
            bool hasNonEmpty = false;
            int_t max = 0;
            for (auto ptr : heaps) {
                if (ptr->empty() == false) {
                    max = std::max(max, *(ptr->begin()));
                    ptr->erase(ptr->begin());
                    hasNonEmpty = true;
                }
            }
            if (hasNonEmpty == false) break;
            assert(heap->empty() == false);
            if (heap->empty() == false) {
                auto ptr = heap->begin();
                max = std::max(max, *ptr);
                heap->erase(ptr);
            }
            result.push_back(max);
        }
        for (auto ptr : heaps) {
            delete ptr;
        }
        result.push_back(vals[vtx]);
        for (int_t x : result) heap->insert(x);
    }
    int main() {
        scanf("%lld", &n);
        for (int_t i = 1; i <= n; i++) scanf("%lld", &vals[i]);
        for (int_t i = 2; i <= n; i++) {
            int_t x;
            scanf("%lld", &x);
            graph[x].push_back(i);
        }
        depth[1] = 1;
        DFS1(1);
        auto heap = new heap_t;
        DFS2(1, heap);
        int_t result = std::accumulate(heap->begin(), heap->end(), 0ll);
        cout << result << endl;
        return 0;
    }

     

  • CF1153D Serval and Rooted Tree

    又是一道送分题…没救了

    可能会考虑二分答案?

    二分一个答案x,把大于等于x的数字设置为1,其他设置为0,然后设$f(x)$表示使得x号点为1,那么x的子树内的叶子节点至少需要几个1.

    然后发现后面这个check和前面二分的x没有任何关系。

    然后直接跑出来f(1),我们就知道了要让根节点最大,我们至少需要几个1.

    然后把f(1)从大到小钦定给k,k-1,k-2…1。最后一个被钦定的元素就是答案。

    #include <iostream>
    #include <vector>
    using int_t = int;
    using std::cin;
    using std::cout;
    using std::endl;
    
    const int_t LARGE = 1e6;
    int_t opt[LARGE + 1];
    std::vector<int_t> graph[LARGE + 1];
    bool isLeaf[LARGE + 1];
    int_t n;
    int_t DFS(int_t vtx) {
        if (isLeaf[vtx]) return 1;
        if (opt[vtx] == 0) {
            int_t result = 0;
            for (int_t to : graph[vtx]) result += DFS(to);
            return result;
        } else {
            int_t result = 0x7fffffff;
            for (int_t to : graph[vtx]) result = std::min(result, DFS(to));
            return result;
        }
    }
    int main() {
        scanf("%d", &n);
        for (int i = 1; i <= n; i++) {
            scanf("%d", &opt[i]);
        }
        for (int i = 2; i <= n; i++) {
            int parent;
            scanf("%d", &parent);
            graph[parent].push_back(i);
        }
        int_t count = 0;
        for (int i = 1; i <= n; i++)
            if (graph[i].empty()) {
                isLeaf[i] = true;
                count++;
            }
        cout << count + 1 - DFS(1) << endl;
        return 0;
    }

     

  • CF1153C Serval and Parenthesis Sequence

    普及题我都不会做…我还能说什么…

    首先原题等价于删掉首尾后,剩下的部分是一个合法的括号序列。

    所以先判掉首尾不合法。

    然后从第2个元素扫到第n-2个元素,统计出空白的位置和前缀和(记左括号为1,右括号为-1)

    如果前缀和为负,那么就先安排上一定数量的左括号。

    如果前缀和为正,那么就先安排上一定数量的右括号。

    如果前缀和为0,那么左右括号安排相等的数量。

    然后我们知道了左右括号各需要多少个,从头开始扫,遇到空位优先放左括号,放完了再放右括号。

    最后检查一遍是否合法即可。

    #include <assert.h>
    #include <cstdlib>
    #include <iostream>
    using int_t = long long int;
    using std::cin;
    using std::cout;
    using std::endl;
    
    const int_t LARGE = 1e6;
    char str[LARGE + 1];
    int_t val[LARGE + 1];
    int_t n;
    void fail() {
        cout << ":(";
        exit(0);
    }
    int main() {
        cin >> n;
        scanf("%s", str + 1);
        int_t count = 0;
        int_t prefix = 0;
        for (int_t i = 2; i <= n - 1; i++) {
            if (str[i] == '(')
                val[i] = 1;
            else if (str[i] == ')')
                val[i] = -1;
            else
                count++;
            prefix += val[i];
        }
        int_t a = 0, b = 0;
        if (prefix < 0)
            a += -prefix;
        else
            b += prefix;
        int_t diff = count - a - b;
    
        if (diff < 0) {
            fail();
    
        } else if (diff % 2)
            fail();
        else {
            a += diff / 2;
            b += diff / 2;
        }
    #ifdef DEBUG
        cout << "a = " << a << " b = " << b << endl;
    #endif
        if (str[1] == ')') fail();
        if (str[n] == '(') fail();
        for (int_t i = 2; i <= n - 1; i++) {
            if (val[i] == 0) {
                if (a > 0) {
                    val[i] = 1;
                    a--;
                } else if (b > 0) {
                    val[i] = -1;
                    b--;
                }
            }
        }
        if (a || b) fail();
        val[1] = 1;
        val[n] = -1;
        prefix = 0;
        for (int_t i = 1; i < n; i++) {
            prefix += val[i];
            if (prefix == 0) fail();
        }
        prefix += val[n];
        if (prefix != 0) fail();
        for (int_t i = 1; i <= n; i++) {
            if (val[i] == 1)
                putchar('(');
            else if (val[i] == -1)
                putchar(')');
            else
                assert(false);
        }
        return 0;
    }

     

  • UOJ176 新年的繁荣

    给定一张完全图,两点之间的边的边权为他们点权按位与的值,求这张图的最大生成树。

    考虑Boruvka(这个名字我现在都拼不下来)生成树算法。

    考虑每一轮如何处理,把所有点权插入到一棵01Trie里,同时备注上这个点所属的联通块。

    然后维护一下每个点的联通块编号的最小值和最大值。

    然后为了防止复杂度爆炸,把01Trie进行一些处理,1的节点全部合并到0上。

    然后每次枚举一个点,在01Trie上查询和这个点按位与值最大,并且与这个点不在联通块内的数。

    #include <algorithm>
    #include <cstdio>
    #include <cstdlib>
    #include <iostream>
    #include <unordered_map>
    #include <utility>
    #include <vector>
    using int_t = long long int;
    using pair_t = std::pair<int_t, int_t>;
    using std::cin;
    using std::cout;
    using std::endl;
    const int_t LARGE = 1e5;
    const int_t INF = 0x7fffffff;
    const int_t BITS = 19;
    namespace allocator {
    const int_t SIZE = LARGE * 100 * 20;
    char buff[SIZE];
    int_t used = 0;
    void* allocate(int_t size) {
        if (used + size >= SIZE) return malloc(size);
        void* res = buff + used;
        used += size;
        return res;
    }
    }  // namespace allocator
    int_t parent[LARGE + 1];
    int n, m;
    int_t vals[LARGE + 1];
    struct Node {
        int_t max = -INF;
        int_t min = +INF;
        int_t id;
        Node* chds[2] = {nullptr, nullptr};
    };
    void insert(int_t val, int_t id, Node* root) {
        Node* curr = root;
        for (int_t i = BITS - 1; i >= 0; i--) {
            int_t bit = (val & (1 << i)) != 0;
            if (curr->chds[bit] == nullptr)
                curr->chds[bit] = new (allocator::allocate(sizeof(Node))) Node;
            curr->max = std::max(curr->max, id);
            curr->min = std::min(curr->min, id);
            curr = curr->chds[bit];
        }
        curr->max = std::max(curr->max, id);
        curr->min = std::min(curr->min, id);
    }
    //合并left和right
    Node* merge(Node* left, Node* right) {
        if (left == nullptr) return right;
        if (right == nullptr) return left;
        Node* next = new (allocator::allocate(sizeof(Node))) Node(*left);
        next->max = std::max(next->max, right->max);
        next->min = std::min(next->min, right->min);
        next->chds[0] = merge(left->chds[0], right->chds[0]);
        next->chds[1] = merge(left->chds[1], right->chds[1]);
        return next;
    }
    void DFS(Node* root) {
        if (root == nullptr) return;
        DFS(root->chds[0]);
        DFS(root->chds[1]);
        root->chds[0] = merge(root->chds[0], root->chds[1]);
    }
    //返回val与Trie树中的数的最大按位与值,要求不能走req的联通快
    pair_t maxAnd(int_t val, int_t req, Node* root) {
        Node* curr = root;
        int_t result = 0;
        for (int_t i = BITS - 1; i >= 0; i--) {
            if (curr == nullptr) return pair_t(-1, 0);
            int_t bit = (val & (1 << i)) != 0;
            if (curr->chds[1] && bit == 1 &&
                ((curr->chds[1]->max == curr->chds[1]->min &&
                  curr->chds[1]->max != req) ||
                 (curr->chds[1]->max != curr->chds[1]->min))) {
                curr = curr->chds[1];
                result |= (1 << i);
            } else {
                curr = curr->chds[0];
            }
        }
        if (curr->min == req)
            return pair_t(result, curr->max);
        else
            return pair_t(result, curr->min);
    }
    
    int_t find(int_t x) {
        if (x == parent[x]) return x;
        return parent[x] = find(parent[x]);
    }
    int main() {
        scanf("%d%d", &n, &m);
        for (int_t i = 1; i <= n; i++) {
            scanf("%lld", &vals[i]);
            parent[i] = i;
        }
        int_t result = 0;
        while (true) {
            allocator::used = 0;
            Node* root = new (allocator::allocate(sizeof(Node))) Node;
            struct Edge {
                int_t from;
                int_t to;
                int_t weight;
            };
            static Edge edges[LARGE + 1];
            for (int_t i = 1; i <= n; i++) {
                int_t parent = ::find(i);
                insert(vals[i], parent, root);
                edges[i].weight = -INF;
            }
            DFS(root);
            //枚举联通块计算答案
            for (int_t i = 1; i <= n; i++) {
                int_t parent = find(i);
                pair_t res = maxAnd(vals[i], parent, root);
                if (res.second != -1) {
                    if (res.first > edges[parent].weight) {
                        edges[parent] = Edge{i, res.second, res.first};
                    }
                }
            }
            bool flag = false;
            for (int_t i = 1; i <= n; i++) {
                auto& thiz = edges[i];
                if (thiz.weight != -INF) {
                    if (find(thiz.from) != find(thiz.to)) {
                        ::parent[find(thiz.from)] = find(thiz.to);
                        result += thiz.weight;
                        flag = true;
                    }
                }
            }
            if (flag == false) break;
        }
        cout << result << endl;
        return 0;
    }

     

  • 九省联考2018 IIIDX

    首先可以根据题意构建出一个森林,其中i号节点是$\frac i k$的子节点,然后要求把给定的n个权值分配到这n个点上,满足每个点的权值不超过其所有子节点的权值。

    考虑一种做法,首先建树,然后求出以每个节点为根的子树大小。

    然后把给定的权值从大到小排序,然后去重并统计一下每一个元素出现的次数,可以得到一个数组$f_i$,i表示严格第i大的权值出现的次数.

    然后把f数组求一个前缀和$F_i$,表示权值严格前i大的元素的出现次数。

    因为$F_i$是一个正序列的前缀和,所以$F_i$一定是递增的.

     

    然后由于题目要求字典序最大,所以我们按照节点编号从小到大的顺序给每一个节点分配权值。

    现在到了i号节点,设$size_i$是以i号节点为根的子树大小,那么这棵子树一共需要$size_i$个数,并且满足其他所有的数都不小于树根的数值。

    所以在$F_i$中倒着找一个位置$p$,满足$F_p \geq size_i$,并且使得$p$尽量的小(因为我们要使得编号尽量的大)。

    即在$F_i$找一个位置$p$,满足min($F_p$,$F_{p+1}$….$F_{n}$)不小于$size_i$,并且$p$尽可能的小.

    这样的意思就是说,我们找到了一个位置,前面有足够i这棵子树用的元素,同时这个值还尽可能的大。

    然后,我们把$p$位置的值留给$i$号点,然后把i到最后的位置的数量全部减掉$size_i$,因为我们给以$i$为根的子树分配了$size_i$个节点。

    但是有一点要注意。

    假设2是1的子节点,那么我们处理完1要处理2之前,需要先撤销掉在处理1时扣掉的$size_1-1$个值,因为那些位置是给1这整颗子树留的,现在我们在处理1的一颗子树,所以我们应该把在处理1时为了1的子节点而多扣掉的$size_1-1$个数加回来。

    至于为什么要在1处扣掉$size_1$而不是1?

    因为我们处理完1之后,接下来不一定要处理1的子节点。

    因为我们是按照编号序贪心,而不是按照DFS序贪心。

    如果是按照DFS序贪心的话,我们直接给1号点扣掉1,然后去处理1的子树即可,但是这样做是错误的,我们这样做只能保证按照DFS序排字典序最大。

    假设2不是1的子节点,而是兄弟节点,或者是在另一颗树里。

    所以我们要在1处减掉整颗子树的size,这样在处理2的时候,就不会影响1的子树内的结果了(因为1的子树需要的位置已经在1分配好了)

    这也解释了为什么要在$F_i$中倒着找的原因,就是尽可能的不去影响前面的子树。

    区间减和最长的最小值大于等于某个数的后缀可以用线段树维护。

    复杂度$O(nlogn)$.

     

  • NOIP2018 赛道修建

    zz般的贪心题。

    二分答案,然后考虑最大化长度超过x的赛道数量。

    从树根开始DFS,当前到了点vtx,一条赛道如果经过点vtx,要么以vtx为一个端点,要么两个端点分别在vtx的两棵子树内,要么一个端点在vtx的字数内,另一个端点在vtx上面。

    先考虑一个端点是vtx的情况。

    如果一条边(vtx,to),以to为根的没有被覆盖的最长的距离+(vtx,to)的边权超过了x,那么这条路径就被覆盖掉了。

    最后拿出来vtx所有没被覆盖的子树,把这些子树内到树根最长的没被覆盖的距离扔到一个multiset里,然后每次从mukltiset中拿出一个元素dis,在multiset中找一个加上dis后够了x并且最小的元素,然后把这个元素和x一起删掉,这又是覆盖了一条路径(如果找不到,就直接删掉dis).

    最后把vtx所有没被覆盖的子树的路径取个最大值,返回,作为以vtx为根的没被覆盖的最长路径长度。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <map>
    #include <set>
    #include <functional>
    #include <assert.h>
    using int_t = long long int;
    
    using std::cin;
    using std::cout;
    using std::endl;
    
    const int_t LARGE = 50000;
    const int_t INF = 0x7fffffffff;
    struct Edge
    {
        int_t from;
        int_t to;
        int_t weight;
        int_t id;
    };
    std::vector<Edge> graph[LARGE + 1];
    int_t n, m;
    
    int_t DFS0(int_t vtx, int_t from, int_t limit, int_t *result)
    {
        std::multiset<int_t> set;
        for (const auto &edge : graph[vtx])
        {
            if (edge.to == from)
                continue;
            int_t length = DFS0(edge.to, vtx, limit, result) + edge.weight;
            if (length >= limit)
                *result += 1;
            else
            {
                set.insert(length);
            }
        }
        int_t maxDis = 0;
        while (set.empty() == false)
        {
            auto ptr = set.begin();
            set.erase(ptr);
            int_t exp_len = limit - *ptr;
            decltype(set.begin()) req_ptr;
            if ((req_ptr = set.lower_bound(exp_len)) != set.end())
            {
                *result += 1;
                set.erase(req_ptr);
            }
            else
            {
                maxDis = std::max(maxDis, *ptr);
            }
        }
        return maxDis;
    }
    
    bool check(int_t x)
    {
        int_t result = 0;
        DFS0(1, -1, x, &result);
        return result >= m;
    }
    
    int main()
    {
        cin >> n >> m;
        int_t right = 0;
        for (int_t i = 1; i <= n - 1; i++)
        {
            int_t from, to, val;
            cin >> from >> to >> val;
            graph[from].push_back(Edge{from, to, val, i});
            graph[to].push_back(Edge{to, from, val, i});
            right += val;
        }
        int_t left = 1;
        int_t result = 0;
        while (left + 1 < right)
        {
            int_t mid = (left + right) / 2;
            if (check(mid))
            {
                result = std::max(result, mid);
                left = mid + 1;
            }
            else
            {
                right = mid - 1;
            }
        }
        for (int_t i = left; i <= right; i++)
            if (check(i))
                result = std::max(result, i);
        cout << result << endl;
        return 0;
    }

     

  • NOI2014 起床困难综合征

    贪心。

    首先预处理出输入的某一位为1或者为0的时候,经过这些门,这一位会变成1还是0

    然后考虑直接贪心,一个二进制位为1的情况下,比它低的二进制位再怎么多也不可能凑出来个比它大的数。

    从高到低枚举m的二进制位,如果这一位设置为0的时候答案就能出来1,那么就设置为0,否则如果这一位设置为1答案才能出来1,那么要考虑,如果这一位设置为了1,而且已经设置好了的位所构成的二进制数不会超过m的时候,就把这一位设置为1,否则,这一位只能设置为0(否则会超过m的限制,因为一个二进制位如果为1,那么比它第的位无论如何都不可能比他大)。

    最后处理完了之后,注意这只是考虑了m范围内的二进制位对答案产生的影响,然而如果某扇门造成了答案大于m,我们不会考虑到这种情况,所以,最后答案需要或上初始攻击力设置为0的时候答案(因为比m高的二进制位只能设置为0)。

    #include <iostream>
    #include <algorithm>
    #include <cstdio>
    #include <string>
    #include <inttypes.h>
    #include <cmath>
    typedef long long int int_t;
    
    using std::cin;
    using std::endl;
    using std::cout;
    uint32_t on = 0xffffffff;
    uint32_t off = 0;
    int_t n , m;
    int main() {
    	cin >> n >> m;
    	for(int_t i = 1; i <= n; i++) {
    		std::string str;
    		int_t val;
    		cin >> str >> val;
    		if(str[0] == 'X') {
    			on ^= val;
    			off ^= val;
    		} else if(str[0] == 'A') {
    			on &= val;
    			off &= val;
    		} else if(str[0] == 'O') {
    			on |= val;
    			off |= val;
    		}
    	}
    	if(m == 0) {
    		cout << off << endl;
    		return 0;
    	}
    //	cout << on << endl << off << endl;
    	int_t result = 0;
    	int_t high = log2(m);
    	int_t used = 0;
    //	cout << high << endl;
    	for(int_t i = high;i >= 0;i--) {
    		if(off & (1 << i)){
    			result |= (1 << i);
    		} else if((used | (1 << i)) <= m && (on & (1 << i))){
    			used |= (1 << i);
    			result |= (1 << i);
    		}
    	}
    	cout << (result | off) << endl;
    	return 0;
    }

     

  • HNOI2003 消防局的设立

    贪心,每次选择一个深度最大而且没被覆盖的点,然后覆盖掉这个点的祖父节点。

    #include <iostream>
    #include <algorithm>
    #include <vector>
    #include <cstring>
    #include <queue>
    #include <utility>
    
    using int_t = long long int;
    using pair_t = std::pair<int_t, int_t>;
    
    using std::cin;
    using std::cout;
    using std::endl;
    
    const int_t LARGE = 1000;
    const int_t INF = 0x7fffffff;
    std::vector<int_t> graph[LARGE + 1];
    
    int_t n;
    int_t depth[LARGE + 1];
    int_t parent[LARGE + 1];
    bool marked[LARGE + 1];
    std::priority_queue<pair_t> heap;
    
    void DFS(int_t vertex, int_t from = 0, int_t depth = 1)
    {
        parent[vertex] = from;
        ::depth[vertex] = depth;
        heap.push(pair_t(depth, vertex));
        for (int_t to : graph[vertex])
        {
            if (to != from)
            {
                DFS(to, vertex, depth + 1);
            }
        }
    }
    int main()
    {
        cin >> n;
        for (int_t i = 2; i <= n; i++)
        {
            int_t x;
            cin >> x;
            graph[i].push_back(x);
            graph[x].push_back(i);
        }
        DFS(1);
        int_t result = 0;
        while (heap.empty() == false)
        {
            auto front = heap.top();
            heap.pop();
            while (heap.empty() == false && marked[front.second])
            {
                front = heap.top();
                heap.pop();
            }
            if (heap.empty())
                break;
            int_t marking = parent[parent[front.second]];
            if (marking == 0)
                marking = 1;
            marked[marking] = true;
            result += 1;
            // cout << "marking " << marking << endl;
            for (auto chd : graph[marking])
            {
                marked[chd] = true;
                for (auto grand : graph[chd])
                {
                    marked[grand] = true;
                }
            }
        }
        cout << result << endl;
        return 0;
    }