forked from rajatgoyal715/Hackerrank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCuttingBoards.java
75 lines (72 loc) · 2.18 KB
/
CuttingBoards.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
// BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// int t = Integer.parseInt(br.readLine());
StringBuilder sb = new StringBuilder("");
while(t--!=0){
int m = sc.nextInt();
int n = sc.nextInt();
// String s1[] = br.readLine().split(" ");
// int m = Integer.parseInt(s1[0]);
// int n = Integer.parseInt(s1[1]);
long y[] = new long[m-1];
// String s2[] = br.readLine().split(" ");
for(int i=0;i<m-1;i++){
y[i] = sc.nextLong();
// y[i] = Integer.parseInt(s2[i]);
}
long x[] = new long[n-1];
// String s3[] = br.readLine().split(" ");
for(int i=0;i<n-1;i++){
x[i] = sc.nextLong();
// x[i] = Integer.parseInt(s3[i]);
}
sb.append(cost(m, n, y, x) + "\n");
}
System.out.println(sb.toString());
}
public static long cost(int m, int n, long[] y, long[] x){
Arrays.sort(y);
Arrays.sort(x);
int horizontal = 1;
int vertical = 1;
int i=m-2;
int j=n-2;
long cost = 0;
long mod = 1000000007;
while(i>=0&&j>=0){
if(y[i]>=x[j]){
cost += vertical*y[i];
// if(cost>=mod) cost%=mod;
i--;
horizontal++;
}
else{
cost += horizontal*x[j];
// if(cost>=mod) cost%=mod;
j--;
vertical++;
}
}
while(j>=0){
cost += horizontal*x[j];
// if(cost>=mod) cost%=mod;
j--;
vertical++;
}
while(i>=0){
cost += vertical*y[i];
// if(cost>=mod) cost%=mod;
i--;
horizontal++;
}
return cost%mod;
}
}