Change language:
Manasa and her friends go hiking. She found a small river lined up with stones with numerical values. She began to walk along the river and found that the numbers on the adjacent two stones increased.AOrBThere is a treasure at the end of the river. If Manasa can guess the value on the last stone, the treasure is her. Assuming that the upper value of the first rock is 0, find all possible values of the last stone.
Input Format
The first line contains integers.TIndicates the number of groups of test data.
Each array contains three rows:
The first line containsNRepresents the number of stones
The second line containsA
The third line containsB
Output FormatOutput all possible values on the last stone in ascending order, separated by spaces.
Value Range
1 ≤T≤ 10
1 ≤N,A,B≤ 103
Question:
For the second stone, the possible value is 0 * A + B or a + 0 * B;
For the third stone, the possible values are 0 * A + 2 * B, 1 * A + 1 * B, 2 * A + 0 * B;
.....
For the nth stone, the possible value is 0 * A + (n-1) * B, 1 * A + (n-2) * B ,......, (n-1) * A + 0 * B;
So we only need to enumerate the coefficients of A and B to calculate all the possibilities.
In addition, hashset in Java is not required, and treeset is ordered.
The Code is as follows:
1 import java.io.*; 2 import java.util.*; 3 4 5 public class Solution { 6 7 public static void main(String[] args) { 8 Scanner in = new Scanner(System.in); 9 int t = in.nextInt();10 for(int i = 0; i < t; i++){11 Set<Long> answer= ManasaandStones(in.nextLong(), in.nextLong(), in.nextLong());12 Iterator<Long> iterator = answer.iterator();13 while(iterator.hasNext()){14 System.out.printf("%d ",iterator.next());15 }16 System.out.println();17 }18 }19 20 private static Set<Long> ManasaandStones(long n, long a, long b){21 22 //Write code to solve each of the test over here23 if(a > b){24 long temp = b;25 b = a;26 a = temp;27 }28 Set<Long> hs = new TreeSet<Long>();29 for(int i = 0;i <= n-1;i++){30 hs.add(i*b+(n-1-i)*a);31 }32 return hs; 33 }34 35 36 }