【PAT-A】1002. A+B for Polynomials 写题记录

思路:

第一次输入原样输入,第二次输入时,直接将相同指数的系数相加,并查找有没有已存在的指数,统计系数为0的个数。

因为队列无法直接删除系数为0的项,故0项最后输出的时候再处理。

注意最后的格式

PS.题目有个瑕疵,未说明指数是否按降序输入与输出,因此最开始构思时想的是用优先队列。

#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 1010;

int main(){
	int K1, K2, p=0;
	priority_queue<int> b;  //b存放指数 
	double a[MAXN] = {0};  //a存放系数 
	bool vis[MAXN] = {false};  //vis用于判断指数是否重复出现 
	scanf("%d",&K1);
	for (int i=0; i<K1; i++){
		int n;
		double x;
		scanf("%d%lf",&n,&x);
		b.push(n);  //把n压入优先队列 
		a[n]=x;   //以指数为下标记录系数 
		vis[n] = true;  //设置flag,true表示此指数已经出现 
	}
	scanf("%d",&K2);
	for (int i=0; i<K2; i++){
		int n;
		double x;
		scanf("%d%lf",&n,&x);
		a[n]+=x;  //系数先相加 
		if (vis[n] == false){  //判断此指数是否重复出现,若未出现过 
			vis[n] = true;  //设置flag 
			b.push(n); //将指数压入优先队列 
		}
		if(a[n]==0){
			p++; 
		} 
	}
	int t=b.size();  //记录此时共有多少个不同的指数  
	int q=1;
	if (t-p == 0){
		printf("0");
	}else printf("%d ",t-p); 
	for (int i=0;i<t;i++){
		if (a[b.top()]!=0){
			if (q<t-p) {
				printf("%d %.1f ",b.top(),a[b.top()]);  //依指数从大到小输出指数与系数 
				q++;
			} else{
				printf("%d %.1f",b.top(),a[b.top()]);
			}		

		}	
		b.pop();		
	}
	/* 
	int t=b.size();  
	printf("%d",t-p); 
	for (int i=0;i<t;i++){
		if (a[b.top()]!=0){
			printf(" %d %.1f",b.top(),a[b.top()]);  
		}	
		b.pop();		
	}
	*/
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_43456345/article/details/83272509