没写过失败树,用它来实现下多路归并排序
测试数据:
4
4 43 545 21 44
6 1 4 8 2 6 0
4 1 -1 3 -6
7 8 1 -5 -6 5 -11 33
第一行代表是几路
后面一共4行,每行第一个数表示这行后面一共有多少个数字
对每行数据先快排,然后用失败树进行多路归并
#include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
using namespace std;
struct node
{
int num, val;
};
struct contrast
{
bool operator() (const node &a,const node &b)
{
return a.val < b.val;
}
} cmp;
vector<vector<node> > record;
int main()
{
int k;
scanf("%d", &k);
int total = 2 * k - 1;
vector<node> tree(total + 1);
vector<int> index(total + 1);
for(int i = 0; i <= total; i++)
index[i] = i;
vector<vector<node>::iterator> head(k);
for(int i = 0; i < k; i++)
{
int num;
scanf("%d", &num);
vector<node> v;
for(int j = 0; j < num; j++)
{
node data;
data.num = i;
scanf("%d", &data.val);
v.push_back(data);
}
sort(v.begin(), v.end(), cmp);
record.push_back(v);
}
for(int i = 0; i < k; i++)
head[i] = record[i].begin();
int tot = k;
for(int i = 0; i < k; i++)
{
tree[total - k + i + 1].val = head[i]->val;
tree[total - k + i + 1].num = head[i]->num;
head[i]++;
if(head[i] == record[i].end())
tot--;
}
while(true)
{
if(tot == 0)
break;
for(int ed = total / 2; ed > 0; ed--)
{
int left = ed * 2, right = ed * 2 + 1;
if(tree[left].val < tree[right].val)
{
tree[ed].val = tree[left].val;
tree[ed].num = tree[left].num;
index[ed] = index[left];
}
else
{
tree[ed].val = tree[right].val;
tree[ed].num = tree[right].num;
index[ed] = index[right];
}
}
printf("%d ", tree[1].val);
if(head[tree[1].num] == record[tree[1].num].end())
{
tot--;
tree[index[1]].num = -1;
tree[index[1]].val = INT_MAX;
}
else
{
tree[index[1]].val = head[tree[1].num]->val;
tree[index[1]].num = head[tree[1].num]->num;
head[tree[1].num]++;
}
}
printf("\n");
return 0;
}
输出结果:
-11 -6 -6 -5 -1 0 1 1 1 2 3 4 5 6 8 8 21 33 43 44 545
有个问题是我在
record.push_back(v);后面加head[i] = record[i].begin();让它每次循环的时候head指向每个数据段的头,但是这样程序有错,head感觉指向错误了,不知什么原因
要在这个循环外面给每个head赋值才成....不知道是为什么。。。谁能帮忙解答下