题目链接:http://www.acmore.net/problem.php?id=1504
Description
ZZ不仅喜欢买衣服,还是个吃货,天哪!现在的妹纸是怎么了?╮(╯_╰)╭,ZZ有两个大型橱柜A和B,里面放满了零食,每个橱柜里面有N个方格,每个方格里面放了不同重量的美味,现在ZZ要从A、B里面各取一个方格的美味,可是ZZ不想变得太胖,于是他会尽量的选择重量少的美味,当然不是所有的组合都是ZZ喜欢吃的美味,所以她想了一个特别的方法,他会选出组合重量最小的前M种中选出一种,可是怎么才能算出前M个组合的重量的呢?这个真是个难题,作为ACMer的ZZ竟然不能解决,你能帮帮她么?
Input
有多组测试数据;
第一行给你一个N(N<=400000)和一个M(M<=N),N表示每个壁橱有N个方格,M表示要选出M种方案;
第二行和第三行分别有N个整数,表示每个方格的美味重量(结果保证在int以内)
Output
按照从小到大的顺序输出前M种方案的重量,每种方案占一行
Sample Input
2 21 23 4
Sample Output
45
通过构造得出N个序列的前K大,求所有序列中的前K大,使用优先队列维护一个长度为N的序列,时间复杂度为O(N*log(N))。
其实也是一个STL的问题。
AC代码:
#include<iostream>
#include<set>
#include<queue>
#include<algorithm>
#include<stdio.h>
using namespace std;
#define max 400008
int q[max],w[max];
struct node{
int c,d;
bool operator <(node p) const
{
return q[p.c]+w[p.d]<q[c]+w[d];
}
}her;
priority_queue<node>myqueue;
int main()
{
int n,m;
while(~scanf("%d%d",&n,&m))
{
for(int i=0;i<n;i++) cin>>q[i];
for(int i=0;i<n;i++) cin>>w[i];
while(!myqueue.empty()) myqueue.pop();
sort(q,q+n);
sort(w,w+n);
for(int i=0;i<n;i++)
{
her.c=i;
her.d=0;
myqueue.push(her);
}
while(m--)
{
her=myqueue.top();
myqueue.pop();
printf("%d\n",q[her.c]+w[her.d]);
if(her.d != n-1){
her.d++;
myqueue.push(her);
}
}
}
return 0;
}
路途中。。。。。