题意:
输入m个数集,每个含n个数,求从每个集合取一个数后,按非降序输出前n小的和;
思路:
1.优先队列
2.堆
1.优先队列
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<algorithm>
#include<queue>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n, m, i,x,j,sum;
int a[2005];
scanf("%d%d",&n,&m);
priority_queue<int,vector<int >,greater<int> > p;
priority_queue<int,vector<int >,less<int> > q;
for(i = 0; i < m; i++)
{
scanf("%d",&x);
p.push(x);
}
for(i = 1; i < n; i++)
{
for(j = 0; j < m;j++)
{
scanf("%d",&a[j]);
}
while(!p.empty())
{
sum = p.top();
p.pop();
for(j = 0; j < m; j++)
{
if(q.size()==m&&q.top()> sum+a[j])
{
q.pop();
q.push(sum+a[j]);
}
else if(q.size() < m)
{
q.push(sum+a[j]);
}
}
}
while(!q.empty())
{
p.push(q.top());
q.pop();
}
}
for(i = 0; i < m; i++)
{
printf("%d",p.top());
p.pop();
if(i < m-1)
printf(" ");
}
printf("\n");
}
return 0;
}
2.堆——转载
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<climits>
#include<list>
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
int now[2200];
int temp[2200];
int heap[2200];
void max_heapify(int *arr,int root,int n)
{
int left=root*2;
int right=left+1;
int largest=root;
if(left<=n&&arr[left]>arr[root])
{
largest=left;
}
if(right<=n&&arr[right]>arr[largest])
{
largest=right;
}
if(largest!=root)
{
int t=arr[root];
arr[root]=arr[largest];
arr[largest]=t;
max_heapify(arr,largest,n);
}
}
void build_heap(int *arr,int n)
{
int i;
for(i=n/2+1;i>=1;--i)
{
max_heapify(arr,i,n);
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
int m,n;
scanf("%d%d",&m,&n);
int i;
int j;
mem(temp);
mem(heap);
for(i=1;i<=n;++i)
{
scanf("%d",&heap[i]);
}
build_heap(heap,n);
for(i=1;i<m;++i)
{
for(j=1;j<=n;++j)
{
scanf("%d",&now[j]);
}
sort(now+1,now+n+1);
for(j=1;j<=n;++j)
{
temp[j]=heap[j]+now[1];
}
// build_heap(temp,n);
for(j=2;j<=n;++j)
{
int k;
int flag=1;
for(k=1;k<=n;++k)
{
int tmp=heap[k]+now[j];
if(tmp<temp[1])
{
temp[1]=tmp;
max_heapify(temp,1,n);
flag=0;
}
}
if(flag)
{
break;
}
}
for(j=1;j<=n;++j)
{
heap[j]=temp[j];
}
}
sort(heap+1,heap+n+1);
for(i=1;i<=n;++i)
{
if(i!=1)
{
printf(" ");
}
printf("%d",heap[i]);
}
printf("\n");
}
}