• UVA 11997


    UVA 11997 - K Smallest Sums

    题目链接

    题意:给定k个数组,每一个数组k个数字,要求每一个数字选出一个数字,构成和,这样一共同拥有kk种情况,要求输出最小的k个和

    思路:事实上仅仅要能求出2组的前k个值,然后不断两两合并就能够了,由于对于每两组,最后答案肯定是拿前k小的去组合。然后问题就变成怎么求2组下的情况了,利用一个优先队列维护,和作为优先级,先把原数组都从小到大排序好了,那么先把a[i] + b[0] (i < k)入队,然后往后取k个,每次取完之后,拿最小那个在把b往后推一个,这样保证每次队列中都会有当前的最小值存在,利用优先队列取出就可以,总复杂度为O(k2log(k))

    代码:

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    #include <queue>
    using namespace std;
    
    const int N = 755;
    
    int n, a[N][N];
    struct State {
        int b, sum;
        State() {}
        State(int b, int sum) {
    	this->b = b;
    	this->sum = sum;
        }
        bool operator < (const State& c) const {
    	return sum > c.sum;
        }
    };
    
    void merge(int *a, int * b) {
        priority_queue<State> Q;
        for (int i = 0; i < n; i++)
    	Q.push(State(0, a[i] + b[0]));
        for (int i = 0; i < n; i++) {
    	State now = Q.top();
    	a[i] = now.sum;
    	Q.pop();
    	Q.push(State(now.b + 1, now.sum - b[now.b] + b[now.b + 1]));
        }
    }
    
    int main() {
        while (~scanf("%d", &n)) {
    	for (int i = 0; i < n; i++) {
    	    for (int j = 0; j < n; j++)
    		scanf("%d", &a[i][j]);
    	    sort(a[i], a[i] + n);
    	}
    	for (int i = 1; i < n; i++)
    	    merge(a[0], a[i]);
    	for (int i = 0; i < n - 1; i++)
    	    printf("%d ", a[0][i]);
    	printf("%d
    ", a[0][n - 1]);
        }
        return 0;
    }


  • 相关阅读:
    制作Autorun的CD
    Sybase ASE MDA tables 装不上怎么办?
    对于TStringList.Find函数,我有话要说
    HH.exe CHM Operator Command.
    Delphi 7的一些常用的快捷键
    Explain Plan
    在Delphi中的Log
    subst windows下实用的磁盘映射工具
    Excel 2007 如何冻结多行&多列
    LinqToDataTable[转]
  • 原文地址:https://www.cnblogs.com/gcczhongduan/p/4011956.html
Copyright © 2020-2023  润新知