A sequence S = {s1, s2, ..., sn} is called heapable if there exists a binary tree Twith n nodes such that every node is labelled with exactly one element from the sequence S, and for every non-root node si and its parent sj, sj ≤ si and j < ihold. Each element in sequence S can be used to label a node in tree T only once.
Chiaki has a sequence a1, a2, ..., an, she would like to decompose it into a minimum number of heapable subsequences.
Note that a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements.
InputThere are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:
The first line contain an integer n (1 ≤ n ≤ 105) — the length of the sequence.
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ n).
It is guaranteed that the sum of all n does not exceed 2 × 106.
<h4< dd="">OutputFor each test case, output an integer m denoting the minimum number of heapable subsequences in the first line. For the next m lines, first output an integer Ci, indicating the length of the subsequence. Then output Ci integers Pi1, Pi2, ..., PiCiin increasing order on the same line, where Pij means the index of the j-th element of the i-th subsequence in the original sequence.
<h4< dd="">Sample Input4 4 1 2 3 4 4 2 4 3 1 4 1 1 1 1 5 3 2 1 4 1<h4< dd="">Sample Output
1 4 1 2 3 4 2 3 1 2 3 1 4 1 4 1 2 3 4 3 2 1 4 1 2 2 3 5
题意: 给你一个序列 你需要用这个序列的元素生成尽量小的最小堆 。 对于一个堆的要求就是 父节点一定要小于等于子节点
并且父节点的在原序列中的下标一定要小于子节点。
思路: 我们贪心每一个给的数值, 如果他的后边有大于等于他的值那么就把它们放进一个堆中,。
具体的实现我们可以用vector 和 set 来实现。 对于每一个数值 我们在set 中找到它应该属于哪一个堆 如果 它小于 set中所有堆的当前父节点。(当前父节点 就是因为父节点的两个子节点满了的情况就要在set中删除当前父节点)那么 就肯定要再开辟一个堆。
但是要注意的是当一个父节点的出度为2 的时候 ,这个父节点 就不能作为标准寻找。
但是还要注意时间 好像特别卡时间。
代码:
#include<stdio.h>
#include<string.h>
#include<vector>
#include<set>
#include<iostream>
#include<algorithm>
#define N 100005
using namespace std;
int a[N],inde[N];
struct node
{
int first;
int second;
}p;
bool operator <(node aa,node bb)
{
if(a[aa.second]==a[bb.second]) return aa.second<bb.second;
else return a[aa.second]<a[bb.second];
}
vector<int >ve[N];
set<node >se;
set<node >::iterator it;
int n;
int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
scanf("%d",&n);
for(int i=0;i<=n;i++) inde[i]=0;
//for(int i=1;i<=n;i++) scanf("%d",&a[i]);
se.clear();
int cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
p.second=i;
it=se.upper_bound(p);
if(it==se.begin())
{
p.first=++cnt;
se.insert(p);
ve[cnt].push_back(i);
}
else
{
it--;
p=*it;
inde[it->second]++;
if(inde[it->second]==2)
{
se.erase(it);
}
p.second=i;
se.insert(p);
ve[p.first].push_back(i);
}
}
printf("%d\n",cnt);
for(int i=1;i<=cnt;i++)
{
printf("%d",ve[i].size());
int size=ve[i].size();
for(int j=0;j<size;j++)
{
printf(" %d",ve[i][j]);
}
printf("\n");
ve[i].clear();
//cout<<endl;
}
}
return 0;
}