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

鏈接: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;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章