TopCoder problem "PairwiseSums" used in SRM 182 (Division I Level Three)



Problem Statement

    

Given a list of numbers, A = {a0, a1, ..., an-1}, its pairwise sums P are defined to be all numbers of the form ai + aj for 0 <= i < j < n. For example, if

  • A = {1,2,3,4},
then
  • P = {1+2, 1+3, 1+4, 2+3, 2+4, 3+4} = {3, 4, 5, 5, 6, 7}.
The order of the terms in P is ignored, and both A and P may contain duplicates.

In general, it is very easy to compute the pairwise sums of a list, but it is much more difficult to perform this operation in reverse, extracting the original list given its pairwise sums. That is where you come in. Create a class PairwiseSums that contains a method reverse, which takes a String[] sums. Each element in sums will consist of space-separated integers. The method should consider the list P containing all the integers in all the elements of sums. If there is exactly one non-decreasing int[] of non-negative integers, A, such that P contains precisely the pairwise sums for A, the method should return A. Otherwise, it should return an empty int[].

 

Definition

    
Class:PairwiseSums
Method:reverse
Parameters:String[]
Returns:int[]
Method signature:int[] reverse(String[] sums)
(be sure your method is public)
    
 

Constraints

-sums will contain between 1 and 50 elements inclusive.
-Each element of sums will contain between 1 and 50 characters inclusive.
-There will be a total of at least three integers in sums.
-Each element of sums will contain at least one integer.
-Each character in sums will either be a space (' '), or a digit ('0'-'9').
-Each integer in sums will be between 0 and 1000 inclusive, and will have no leading 0's.
-Each element of sums will have precisely one space between consecutive integers, and will have no leading or trailing spaces.
 

Examples

0)
    
{"3 5 4 7 6 5"}
Returns: { 1,  2,  3,  4 }
This is the example from the problem statement.
1)
    
{"0", "1000", "1000"}
Returns: { 0,  0,  1000 }
Note that A can contain 0 and duplicates, but it cannot contain negative integers or fractions.
2)
    
{"15 30 45 60"}
Returns: { }
There exists no A whose collection of pairwise sums contains precisely four elements.
3)
    
{"5 6 7 9 10 11"}
Returns: { }
A could be either {1,4,5,6} or {2,3,4,7}, so {} is returned.
4)
    
{"910 689 882 565 922 815 457 674 495 653 755 948",
 "631 988 881 523 740 561 719 727 410 767 660 302",
 "519 340 498 603 960 853 495 712 533 691 643 536",
 "178 395 216 374 893 535 752 573 731 428 645 466",
 "624 287 108 266 325 483 304"}
Returns: { 35,  73,  143,  231,  252,  267,  393,  422,  460,  488,  500 }

Problem url:

http://www.topcoder.com/stat?c=problem_statement&pm=595

Problem stats url:

http://www.topcoder.com/tc?module=ProblemDetail&rd=4730&pm=595

Writer:

dgarthur

Testers:

lbackstrom , brett1479

Problem categories:

Brute Force, Math