解法一:双指针

双指针遍历两个多项式,按照指数大小求和加入最终结果 ans 。注意处理和为0的情况和输出格式。

  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.util.ArrayList;
  5. public class Main {
  6. private static float EXP = 1e-5f;
  7. public static void main(String[] args) throws IOException {
  8. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
  9. String[] input = reader.readLine().split(" ");
  10. int lenA = Integer.parseInt(input[0]);
  11. ArrayList<Item> A = new ArrayList<>(lenA);
  12. for (int i = 1; i <= lenA; ++i) {
  13. int exponent = Integer.parseInt(input[i * 2 - 1]);
  14. float coef = Float.parseFloat(input[i * 2]);
  15. A.add(new Item(exponent, coef));
  16. }
  17. input = reader.readLine().split(" ");
  18. int lenB = Integer.parseInt(input[0]);
  19. ArrayList<Item> B = new ArrayList<>(lenB);
  20. for (int i = 1; i <= lenB; ++i) {
  21. int exponent = Integer.parseInt(input[i * 2 - 1]);
  22. float coef = Float.parseFloat(input[i * 2]);
  23. B.add(new Item(exponent, coef));
  24. }
  25. ArrayList<Item> ans = new ArrayList<>(lenA);
  26. int p1 = 0, p2 = 0;
  27. while ((p1 < lenA) && (p2 < lenB)) {
  28. int flag = A.get(p1).exponent - B.get(p2).exponent;
  29. if (flag > 0) {
  30. ans.add(A.get(p1++));
  31. } else if (flag < 0) {
  32. ans.add(B.get(p2++));
  33. } else {
  34. float sum = A.get(p1).coef + B.get(p2).coef;
  35. if (!equalZero(sum)) {
  36. ans.add(new Item(A.get(p1).exponent, sum));
  37. }
  38. ++p1;
  39. ++p2;
  40. }
  41. }
  42. while (p1 < lenA) {
  43. if (!equalZero(A.get(p1).coef)) {
  44. ans.add(A.get(p1++));
  45. }
  46. }
  47. while (p2 < lenB) {
  48. if (!equalZero(B.get(p2).coef)) {
  49. ans.add(B.get(p2++));
  50. }
  51. }
  52. System.out.print(ans.size());
  53. for (Item i : ans) {
  54. System.out.printf(" %d %.1f", i.exponent, i.coef);
  55. }
  56. }
  57. private static boolean equalZero(float a) {
  58. if (Math.abs(a) < EXP) {
  59. return true;
  60. }
  61. return false;
  62. }
  63. }
  64. class Item {
  65. int exponent;
  66. float coef;
  67. Item() {
  68. coef = 0.0f;
  69. }
  70. Item(int exponent, float coef) {
  71. this.exponent = exponent;
  72. this.coef = coef;
  73. }
  74. }