CS Academy Set Subtraction

题目链接:https://csacademy.com/contest/round-46/task/set-subtraction/

题目大意:给出一个N个数的序列A,将A中每个元素减去X之后我们能够得到一个新序列B。先给出A,B混合的序列C(2*N个元素),求X和原序列。输出任意一个解,或-1表示无解。N < 1000

解题思路:首先能够发现X实际上只能取N个。我们将A排序之后,枚举从第二个数开始到第N+1个数C[i],C[i] - C[1]即是X可取的值。那么我们可以枚举X,然后check。具体check过程可以用multiset来判断。对于C中每个数C[i],如果multiset中既有C[i]也有C[i]+X,那么将两者删除并且将C[i]+X放入结果集中。如果最后结果集元素恰好为N个,那么这就是可行解。

代码:

 1 const int maxn = 1e4 + 5;
 2 int n, a[maxn];
 3 multiset<int> sa;
 4 VI ansv, xs;
 5 
 6 bool check(int x){
 7     multiset<int>::iterator it1, it2;
 8     for(int i = 1; i <= 2 * n; i++){
 9         int u = a[i] + x;
10         it1 = sa.find(u), it2 = sa.find(a[i]);
11         if(it1 != sa.end() && it2 != sa.end()){
12             ansv.push_back(u);
13             sa.erase(it1); 
14             sa.erase(it2);
15         }
16     }
17     if(ansv.size() == n){
18         printf("%d\n", x);
19         for(int i = 0; i < n; i++){
20             printf("%d ", ansv[i]);
21         }
22         return true;
23     }
24     return false;
25 }
26 void solve(){
27     sort(a + 1, a + 2 * n);
28     for(int i = 2; i <= n + 1; i++){
29         sa.clear();
30         ansv.clear();
31         for(int j = 1; j <= 2 * n; j++) sa.insert(a[j]);
32         int x = a[i] - a[1];
33         if(x <= 0) continue;
34         if(check(x)) return;
35     }
36     puts("-1");
37 }
38 int main(){
39     scanf("%d", &n);
40     for(int i = 1; i <= 2 * n; i++) scanf("%d", &a[i]);
41     solve();
42 }

题目:

Set Subtraction

Time limit:  1000 ms
Memory limit:  256 MB

 

You have a set SS of NN integers. You choose a positive value XX and subtract it from every element of SS, obtaining other NN integers. Then you build an array AA of size 2*N2N with the initial elements and the resulting elements, in a random order.

Given AA, find XX and the elements of SS.

Standard input

The first line contains a single integer NN.

The second line contains 2*N2N integers representing the elements of AA.

Standard output

If there is no solution output -11.

Otherwise, print on the first line a single integer XX.

On the second line print the NN elements of SS.

If the solution is not unique you can output any of them.

Constraints and notes

  • 1 \leq N \leq 10001N100
  • 1 \leq A_i \leq 10^91Ai​​109​​ 
  • XX should be positive

 

Input Output Explanation
2
1 2 3 4
2
4 3
 
2
1 2 3 4
1
4 2

Note that any solution is valid.

Both X = 1X=1 and X = 2X=2 are valid.

4
2 5 1 5 4 2 8 5
3
8 5 5 4 
 
4
4 4 2 3 5 1 3 6
1
6 4 4 2 
 
2
1 2 4 4
-1

你可能感兴趣的:(CS Academy Set Subtraction)