题目链接:http://www.patest.cn/contests/pat-a-practise/1002
题目:
时间限制400 ms
内存限制65536 kB
代码长度限制16000 B
判题程序Standard作者CHEN, Yue
This time, you are supposed to find A+B where A and B are two polynomials.
Input
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
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 Input2 1 2.4 0 3.2 2 2 1.5 1 0.5Sample Output3 2 1.5 1 2.9 0 3.2
分析:
这是一道多项式运算的题目,看起来不难,但是有一些注意点:
1)要有分别保存多项式系数和指数的数组
2)对于运算,注意有运算后为0的情况,所以总的个数会减少
3)同时,也有两个多项式全部抵消的情况,即0项结果,那么注意这时要输出的只能是0,而不能是0空格。
以下是我没有注意到格式方面的错误提交后的截图
AC的代码如下:
#include<iostream>
#include<string.h>
using namespace std;
int a[30];//存放指数
double b[30];//存放系数
int main(void){
int i,j,n,temp,flag;
double temp2;
bool added;//如果指数相同则系数相加减
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));//init()
scanf("%d",&n);
for(i = 0; i < n; i++){
scanf("%d",&a[i]);
scanf("%lf",&b[i]);
}
flag = n;
scanf("%d",&n);
for(i = 0; i < n; i++){
added = false;
scanf("%d",&temp);
scanf("%lf",&temp2);
for(j = 0; j < flag; j++){
if(temp == a[j]){//如果指数相同则系数相运算
b[j] += temp2;
added = true;
}
}
if(added == false){//否则就把新的项存下来
a[flag] = temp;
b[flag] = temp2;
flag ++;
}
}
int count = 0;
for(i = 0; i < flag; i++){//统计指数相同后系数变为0即抵消的项数目
if(b[i] == 0)
count++;
}
printf("%d", flag - count);//得到最后的有效的项数目
for(i = 0; i < flag-1; i++){//按指数大小排序
for(j = i + 1; j < flag; j++){
if(a[j] > a[i]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
temp2 = b[i];
b[i] = b[j];
b[j] =temp2;
}
}
}
while(b[flag-1] == 0){
flag --;
}
for(i = 0; i < flag; i++){//格式化输出
if(b[i] != 0){
if(i != flag - 1){
printf(" %d %.1lf",a[i],b[i]);
}
else {
printf(" %d %.1lf\n",a[i],b[i]);
}
}
}
// system("pause");
return 0;
}
当然,这是很早以前写的啦,会有繁琐的地方。
也顺便把王道论坛的答案1002部分放上来吧
#include<stdio.h>
#include<string.h>
using namespace std;
double a[1002];
double b[1002];
int main(void){
int n,i,temp;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&temp);
scanf("%lf",&a[temp]);
}
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d",&temp);
scanf("%lf",&b[temp]);
}
int count = 0;
for(i=0;i<1002;i++){
a[i]+=b[i];
if(a[i]!=0) count++;
}
printf("%d",count);
for(i=1001;i>=0;i--)
if(a[i]!=0){
count--;
printf(count==0?" %d %.1f\n":" %d %.1f",i,a[i]);
}
return 0;
}
——Apie陈小旭