http://acm.hdu.edu.cn/showproblem.php?pid=1270
小希的数表
Problem Description
Gardon昨天给小希布置了一道作业,即根据一张由不超过5000的N(3<=N<=100)个正整数组成的数表两两相加得到N*(N-1)/2个和,然后再将它们排序。例如,如果数表里含有四个数1,3,4,9,那么正确答案是4,5,7,10,12,13。小希做完作业以后出去玩了一阵,可是下午回家时发现原来的那张数表不见了,好在她做出的答案还在,你能帮助她根据她的答案计算出原来的数表么?
Input
包含多组数据,每组数据以一个N开头,接下来的一行有按照大小顺序排列的N*(N-1)/2个数,是小希完成的答案。文件最后以一个0结束。
假设输入保证解的存在性和唯一性。
Output
对于每组数据,输出原来的数表。它们也应当是按照顺序排列的。
Sample Input
4
4 5 7 10 12 13
4
5 6 7 8 9 10
0
Sample Output
1 3 4 9
2 3 4 6
题意:
有一组数列a[],已知两两相加后的结果,就原数列。
思路:
把结果放进一个最小堆,枚举a[1], .那么每次堆顶的元素减去a[1]就是待求数列最小的元素,然后把得出的新数与已求出的数分别相加后,从堆中删除这些数。时间复杂度O(5000n^2)
代码:
#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define MAXN 11000
#define eps (1e-8)
#define INF 1000000000
#define abs(x) ((x) > 0? (x): -(x))
#define sqr(x) ((x) * (x))
#define two(x) (1 << (x))
typedef long long LL;
int n, sum[MAXN], num[MAXN], tn[MAXN];
priority_queue<int> heap;
void init()
{
for (int i = 1; i * 2 <= n * (n - 1); ++i) scanf("%d", &sum[i]);
}
void work()
{
for (num[1] = 1; num[1] * 2 <= sum[1]; ++num[1])
{
memset(tn, 0, sizeof(tn));
while (!heap.empty()) heap.pop();
for (int i = 1; i * 2 <= n * (n - 1); ++i)
{
heap.push(-sum[i]);
++tn[sum[i]];
}
bool flag = true;
for (int i = 2; i <= n && flag; ++i)
{
while (tn[-heap.top()] == 0) heap.pop();
num[i] = -heap.top() - num[1];
--tn[-heap.top()];
heap.pop();
for (int j = 2; j < i && flag; ++j)
{
int x = num[j] + num[i];
if (x > 10000 || tn[x] == 0) flag = false;
else --tn[x];
}
}
if (flag)
{
for (int i = 1; i < n; ++i) printf("%d ", num[i]);
printf("%d\n", num[n]);
break;
}
}
}
int main()
{
while (scanf("%d", &n) != EOF && n)
{
init();
work();
}
return 0;
}