1002. A+B for Polynomials

http://pat.zju.edu.cn/contests/pat-a-practise/1002

这题我一开始想了个极其愚蠢的办法,开两个数组然后把系数存储到对应的数组位置上,两个系数数组循环一遍非零的相加,然后发现这样做效率太低,网上参考了下,发现大神的做法只开一个数组,在从标准终端读数剧的时候就把相应的系数加好。

#include<iostream>
#include<iomanip>
#include<limits>
using namespace std;
#define  MAXF 0
void initarray(double *a,int n)
{
	for(int i=0;i<n;i++){
		a[i]=MAXF;
	}
}
int main()
{
#define N 1001
	double a[N];
	initarray(a,N);
	int k1,k2;
	int count=0;
	int i;
	cin>>k1;
	for(i=0;i<k1;i++){
		int exponent;
		double coefficient;
		cin>>exponent;
		cin>>coefficient;
		a[exponent]+=coefficient;
	}
	cin>>k2;
	for(i=0;i<k2;i++){
		int exponent; 
		double coefficient;
		cin>>exponent;
		cin>>coefficient;
		a[exponent]+=coefficient;
	}
	for(i=0;i<N;i++)
		if(a[i]!=MAXF) count++;
	cout<<count;
	for(i=N-1;i>=0;i--){
		if(a[i]!=MAXF){
			cout<<fixed<<setprecision(1);
			cout<<" "<<i<<" "<<a[i];
		}
	}
	return 0;	
}

我自己编了个代码,有一个测试点未通过

#include <cstdlib>
#include <iostream>
#include <vector>
#include <iomanip>
#include <cstring>

using namespace std;

#define MAX 1000
double coef[MAX];



int main(int argc, char *argv[])
{
    memset(coef,0,sizeof(coef));
    int k1=0,k2=0,N;
    double coeff;
    cin>>k1;
    for(int i=0;i<k1;i++)
    {
            cin>>N>>coeff;
            coef[N]+=coeff;
    }
    cin>>k2;
    for(int i=0;i<k2;i++)
    {
            cin>>N>>coeff;
            coef[N]+=coeff;
    }
    int count=0;
    vector<double> poly;
    for(int i=0;i<MAX;i++)
    {
            if(coef[i])
            {
                 count++;                 
                 poly.push_back(coef[i]);
                 poly.push_back(i);
            }
    }
    cout<<count;
    vector<double>::reverse_iterator it=poly.rbegin();//设为reverse_iterator 
    for(;it!=poly.rend();it++)
    {
          cout<<" "<<(int)*it;
          cout<<fixed<<setprecision(1);
          it++;
          cout<<" "<<*it;
    }
    cout<<endl;
    
    //system("PAUSE");
    return 0;
}


你可能感兴趣的:(1002. A+B for Polynomials)