65,187
社区成员




#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <queue>
using namespace std;
#define ROWS 20
#define COLS 500
int data[ROWS][COLS];
void CreateData()
{
for(int i=0; i<ROWS; i++)
{
for(int j=0; j<COLS;j++)
{
data[i][j] = rand(); //生成随机元素
}
}
for( int i=0; i<ROWS; i++)
sort(data[i],data[i]+COLS, greater<int>()); //对每一行降序排列
}
struct Node
{
int *p; //指向某个列,因为要放入优先队列中,所以要比较大小,就用结构体封装了下
bool operator<(const struct Node &node) const
{
return *p < *node.p;
}
};
void OutMinData( int k)
{
struct Node arr[ROWS];
for(int i=0; i<ROWS;i++)
{
arr[i].p = data[i]; //初始化指针指向各行的首位
}
priority_queue<Node > queue( arr, arr+ROWS ); //使用优先队列,默认是大堆
for( int i=0; i<k&&i<COLS; i++) //算法核心就是这个循环
{
Node temp = queue.top(); //取出队列中最大的元素
cout << *temp.p << " " <<endl;
queue.pop(); //从队列里删除
temp.p++; //对应行的指针后移
queue.push( temp ); //这里面有log(ROWS)次操作,所以算法的总复杂度为O(klog(20))
}
}
int main()
{
CreateData(); //生成数据
int k=500;
OutMinData( k ); //输出k个元素,这里k不要大于列数COL,可以改进,去掉这个限制,不过会让程序不好懂,就没加
}
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <queue>
using namespace std;
#define ROWS 20
#define COLS 500
int data[ROWS][COLS];
void CreateData()
{
for(int i=0; i<ROWS; i++)
{
for(int j=0; j<COLS;j++)
{
data[i][j] = rand();
}
}
for( int i=0; i<ROWS; i++)
sort(data[i],data[i]+COLS, greater<int>()); //降序排列
}
struct Node
{
int *p;
bool operator<(const struct Node &node) const
{
return *p < *node.p;
}
};
void OutMaxData( int k)
{
struct Node arr[ROWS];
for(int i=0; i<ROWS;i++)
{
arr[i].p = data[i]; //初始化指针指向各行的首位
}
priority_queue<Node > queue( arr, arr+ROWS ); //使用优先队列,默认是大堆
for( int i=0; i<k&&i<COLS; i++)
{
Node temp = queue.top();
cout << *temp.p << " " <<endl;
queue.pop();
temp.p++;
queue.push( temp ); //这里面有log(COLS)次操作,所以算法的总复杂度为O(klog(20))
}
}
int main()
{
CreateData(); //生成数据
int k=500;
OutMaxData( k );
}