UVA 11997 - K最小的金额 (DP&转换&&优先队列) 好题

来源:互联网 发布:告白墙源码 编辑:程序博客网 时间:2024/06/06 15:04

 

Submit Problem Stats
uDebug Download as PDF

11997 - K最小的金额


You’re given k arrays, each array has k integers. There are kk ways to pick exactly one element in eacharray and calculate the sum of the integers. Your task is to find the k smallest sums among them.InputThere will be several test cases. The first line of each case contains an integer k (2 ≤ k ≤ 750). Each ofthe following k lines contains k positive integers in each array. Each of these integers does not exceed1,000,000. The input is terminated by end-of-file (EOF).OutputFor each test case, print the k smallest sums, in ascending order

.Sample Input

3

1 8 5

9 2 5

10 7 6

2

1 1

1 2

Sample Output

9 10 12

2 2

 //写了一早上,都没写出来,看了大神的博客,原来大神是用优先队列写的。。。

#include<stdio.h>#include<string.h>#include<queue>#include<algorithm>#define N 800#define INF 0x3f3f3f3f using namespace std;int map[N][N];struct zz{int s;int p;zz(int s,int p):s(s),p(p){}friend bool operator<(zz a,zz b){return a.s>b.s;}};void merge(int *a,int *b,int *c,int n){sort(a,a+n);sort(b,b+n);priority_queue<zz>q;for(int i=0;i<n;i++)q.push(zz(a[i]+b[0],0));for(int i=0;i<n;i++){zz d=q.top();q.pop();c[i]=d.s;q.push(zz(d.s-b[d.p]+b[d.p+1],d.p+1));}}int main(){int n,i,j;while(scanf("%d",&n)!=EOF){for(i=0;i<n;i++)for(j=0;j<n;j++)scanf("%d",&map[i][j]);for(i=1;i<n;i++){merge(map[0],map[i],map[0],n);}for(i=0;i<n;i++){if(i)printf(" ");printf("%d",map[0][i]);}printf("\n");}return 0;}


 

 

//这个代码一直WA,不知为啥。。。经过队友提醒才明白,这组数据过不了。。。

4

1 2 5 100

1 2 8 100

1 8 9 100

1 10 15 100

 

#include<stdio.h>#include<string.h>#define N 800#define ll long long#include<algorithm>using namespace std;int a[800][800];int sum[6400];int main(){int n,i,j,k,m;while(scanf("%d",&n)!=EOF){memset(sum,0,sizeof(sum));for(i=0;i<n;i++)for(j=0;j<n;j++)scanf("%d",&a[i][j]);for(i=0;i<n;i++)sort(a[i],a[i]+n);//for(i=0;i<n;i++)//{//for(j=0;j<n;j++)//printf("%d ",a[i][j]);//printf("\n");//}int num=0;for(i=0;i<n;i++)num+=a[i][0];//printf("--%d\n",num);k=0;for(i=0;i<n;i++)for(j=1;j<n;j++)sum[k++]=a[i][j]-a[i][0];sort(sum,sum+k);//for(i=0;i<k;i++)//printf("%d--",sum[i]);//printf("\n");printf("%d",num);for(i=0;i<n-1;i++)printf(" %d",num+sum[i]);printf("\n");}return 0;}


 

0 0
原创粉丝点击