题目链接
思路:
直接按多项式相乘的方法进行模拟。
我们巧妙的运用一个数组arr
则有arr[q项数 + h项数 ] = (q系数 * h系数);
这样一来最后倒序输出即可。
优化后代码
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int q[][] = new int[2][2];
int h[][] = new int[2][2];
int arr[] = new int[24];
Scanner cin = new Scanner(System.in);
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
q[i][j] = cin.nextInt();
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
h[i][j] = cin.nextInt();
}
}
for(int i = 0;i < 2;i++) {
for(int j = 0;j < 2;j++) {
arr[q[i][1] + h[j][1]] += q[i][0] * h[j][0];
}
}
for(int i = 20;i >= 0;i--) {
if(arr[i] != 0)System.out.println(arr[i] + " " + i);
}
}
}
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int a[] = new int[4];
int b[] = new int[4];
int a1[] = new int[4];
int b1[] = new int[4];
Scanner cin = new Scanner(System.in);
for(int i = 0;i < 4;i++) {
a[i] = cin.nextInt();
b[i] = cin.nextInt();
}
a1[0] = a[0] * a[2];
a1[1] = a[0] * a[3];
a1[2] = a[1] * a[2];
a1[3] = a[1] * a[3];
b1[0] = b[0] + b[2];
b1[1] = b[0] + b[3];
b1[2] = b[1] + b[2];
b1[3] = b[1] + b[3];
int vis[] = new int[5];
for(int i = 0;i < 4;i++) {
if(vis[i] == 1)continue;
for(int j = i + 1;j < 4;j++) {
if(b1[i] == b1[j]) {
a1[i] += a1[j];
a1[j] = 0;
vis[j] = 1;
}
}
}
int cnt = 0;
int t[][] = new int[4][2];
for(int i = 0;i < 4;i++) {
if(a1[i] != 0) {
t[cnt][0] = a1[i];
t[cnt][1] = b1[i];
cnt++;
}
}
Arrays.sort(t, 0, cnt, new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
return o2[1] - o1[1];
}
});
for(int i = 0;i < cnt;i++) {
System.out.println(t[i][0] + " " + t[i][1]);
}
}
}