数组
1 原题
This time, you are supposed to find A+B where A and B are two polynomials.
Input Specification:
Each input file contains one test case. Each case occupies 2 lines, and each line contains the information of a polynomial:
K\ N_1\ a_{N_1}\ N_2\ a_{N_2}\ \dots\ N_K\ a_{N_K}
where K is the number of nonzero terms in the polynomial, N_i and a_{N_i}\ (i=1,2,\dots,K) are the exponents and coefficients, respectively. It is given that 1\le K\le 10,\ 0\le N_K\lt \cdots \lt N_2 \lt N_1 \le 1000.
Output Specification:
For each test case you should output the sum of A and B in one line, with the same format as the input. Notice that there must be NO extra space at the end of each line. Please be accurate to 1 decimal place.
Sample Input:
2 1 2.4 0 3.2
2 2 1.5 1 0.5
Sample Output:
3 2 1.5 1 2.9 0 3.2
代码长度限制:16 KB
时间限制:400 ms
内存限制:64 MB
栈限制:8192 KB
2 代码示例
Java
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
private static final int N = 1010;
private static double[] a = new double[N];
private static double[] b = new double[N];
private static List<Pair> c = new ArrayList<>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
input(scanner, a);
input(scanner, b);
for (int i = N - 1; i >= 0; i--) {
if (a[i] + b[i] != 0) {
c.add(new Pair(i, a[i] + b[i]));
}
}
System.out.print(c.size());
for (Pair pair : c) {
System.out.printf(" %d %.1f", pair.exponent, pair.coefficient);
}
}
private static void input(Scanner scanner, double[] array) {
int n = scanner.nextInt();
while (n-- > 0) {
int exponent = scanner.nextInt();
double coefficient = scanner.nextDouble();
array[exponent] = coefficient;
}
}
private static class Pair {
int exponent;
double coefficient;
Pair(int exponent, double coefficient) {
this.exponent = exponent;
this.coefficient = coefficient;
}
}
}
C++
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 1010;
double a[N], b[N];
vector <pair<int, double>> c; // (expon, coef)
void input(double a[]) {
int n;
scanf("%d", &n);
while (n--) {
int expon;
double coef;
scanf("%d%lf", &expon, &coef);
a[expon] = coef;
}
}
int main() {
input(a);
input(b);
for (int i = N - 1; i >= 0; i--)
if (a[i] + b[i])
c.push_back({i, a[i] + b[i]});
cout << c.size();
for (auto it: c)
printf(" %d %.1f", it.first, it.second);
return 0;
}