ZOJ-3963-Heap Partition(贪心)(STL)

6 篇文章 0 订阅
5 篇文章 0 订阅

链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5595


大致题意:用给出的数列a1,a2,a3....an构造二叉树,满足对于下标i和j,有i<j 且ai<=aj满足ai是aj的父节点,问最少需要构造几棵树,并输出。

正序建树模拟一下,找到小于等于当前权值的一个可插入最大值,成为其子节点,找不到则新建树。


#include <bits/stdc++.h>

using namespace std;

int main()
{
    int T;
    scanf("%d", &T);
    while (T--)
    {
        int n;
        scanf("%d", &n);
        vector<int> a(n), b(n), c(n);
        set< pair<int, int> > se;
        vector< vector<int> > ans;
        set< pair<int, int> >::iterator it;
        for (int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            it = se.lower_bound( {-a[i], -i});
            if (it == se.end())
            {
                ans.push_back(vector<int>(1, i + 1));
                b[i] = ans.size() - 1;
            }
            else
            {
                ans[b[-it->second]].push_back(i + 1);
                b[i] = b[-it->second];
                c[-it->second]++;
                if (c[-it->second] == 2)
                    se.erase(it);
            }
            se.insert( {-a[i], -i});
        }
        printf("%d\n", (int)ans.size());
        for(int i=0,N=ans.size(); i<N; ++i)
        {
            printf("%d", (int)ans[i].size());
            for(int j=0,M=ans[i].size(); j<M; ++j)
                printf(" %d", ans[i][j]);
            puts("");
        }
    }
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值