1002 A+B for Polynomials (25 分)
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 N1 aN1 N2 aN2 ... NK aNK
where K is the number of nonzero terms in the polynomial, Ni and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤NK<⋯<N2<N1≤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
(1)17/25分代码:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int exp;
double coef;
Node(int exp = 0,double coef = 0){
this->exp = exp;
this->coef = coef;
}
// operator < (const Node& a){
// return exp > a.exp;
// }
bool operator == (const Node &a)
{
return exp == a.exp;
}
};
bool cmp(const Node&a, const Node&b)
{
return a.exp > b.exp;
}
vector<Node> a;
vector<Node> b;
vector<Node> ans;
int main()
{
int k,exp;
double coef;
Node node;
cin >> k;
for(int i = 0; i < k; i++){
cin >>exp>>coef;
node = Node(exp,coef);
vector<Node>::iterator it = find(a.begin(),a.end(),node);
if(it!=a.end()){
it->coef += node.coef;
}
else {
a.push_back(node);
}
}
cin >> k;
for(int i = 0; i < k; i++){
cin >>exp>>coef;
node = Node(exp,coef);
vector<Node>::iterator it = find(b.begin(),b.end(),node);
if(it!=b.end()){
it->coef += node.coef;
}
else {
b.push_back(node);
}
}
sort(a.begin(),a.end(),cmp);
sort(b.begin(),b.end(),cmp);
int i,j;
for(i = 0, j = 0; i < a.size()&&j < b.size(); ){
Node x = a[i];
Node y = b[j];
if(x.exp == y.exp){
ans.push_back(Node(x.exp,x.coef+y.coef));
i++;
j++;
}
else if(x.exp > y.exp){
ans.push_back(x);
i++;
}
else {
ans.push_back(y);
j++;
}
}
while(i < a.size()){
ans.push_back(a[i++]);
}
while(j < b.size()){
ans.push_back(b[j++]);
}
printf("%d",ans.size());
for(int i = 0; i < ans.size(); i++){
printf(" %d %.1lf",ans[i].exp, ans[i].coef);
}
return 0;
}
提交时间 | 状态 | 分数 | 题目 | 编译器 | 耗时 | 用户 |
---|---|---|---|---|---|---|
2018/10/30 19:31:03 | 部分正确 | 17 | 1002 | C++ (g++) | 4 ms |
测试点 | 结果 | 耗时 | 内存 |
---|---|---|---|
0 | 答案正确 | 3 ms | 376KB |
1 | 答案正确 | 2 ms | 384KB |
2 | 答案正确 | 2 ms | 512KB |
3 | 答案错误 | 4 ms | 512KB |
4 | 答案错误 | 2 ms | 384KB |
5 | 答案错误 | 2 ms | 384KB |
6 | 答案错误 | 2 ms | 376KB |
(2)写法2:25/25分
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
double p[1001];
int main()
{
int k,exp;
double coef;
cin >> k;
for(int i = 0; i < k; i++){
cin >>exp>>coef;
p[exp] += coef;
}
cin >> k;
for(int i = 0; i < k; i++){
cin >>exp>>coef;
p[exp] += coef;
}
int cnt = 0;
for(int i = 0; i < 1001; i++){
if(p[i]!=0) cnt++;
}
printf("%d",cnt);
for(int i = 1001; i >= 0; i--){
if(p[i]!=0){
printf(" %d %.1lf",i,p[i]);
}
}
return 0;
}