zoukankan      html  css  js  c++  java
  • PTA(Advanced Level)1002.A+B for Polynomials

    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 a**N1 N2 a**N2 ... N**K aNK

    where K is the number of nonzero terms in the polynomial, N**i and aNi (i=1,2,⋯,K) are the exponents and coefficients, respectively. It is given that 1≤K≤10,0≤N**K<⋯<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
    
    思路
    • 统计个数的时候要注意如果两个系数相加为0,最后是不输出的,这里要注意一下,所以先全部读进来再进行统计cnt
    代码
    #include<bits/stdc++.h>
    using namespace std;
    double coefficient[1010] = {0};
    bool vis[1010] = {0};
    int main()
    {
    	int k;
    	int max_coe = -1;
    	int id;
    	double tmp;
    	int cnt = 0; //统计不同系数的个数,要非零
    
    	cin >> k;
    	while(k--)
    	{
    		cin >> id >> tmp;
    		coefficient[id] += tmp;
    		if(!vis[id])
    		{
    			vis[id] = true;
    			cnt++;
    		}
    		max_coe = max(max_coe, id);
    	}
    	cin >> k;
    	while(k--)
    	{
    		cin >> id >> tmp;
    		coefficient[id] += tmp;
    		if(!vis[id])
    		{
    			vis[id] = true;
    			cnt++;
    		}
    		max_coe = max(max_coe, id);
    	}
    
    	cout << cnt << " ";
    	for(int i=max_coe;i>=0;i--)
    	{
    		if(vis[i] && cnt != 1)
    		{
    			cout << i << " " << coefficient[i] << " ";
    		}
    		if(vis[i] && cnt == 1)
    		{
    			cout << i << " " << coefficient[i];
    		}
    		cnt--;
    		if(cnt == 0)
    			break;
    	}
    
    	return 0;
    }
    
    
    引用

    https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000

  • 相关阅读:
    Codeforces Round #276 (Div. 1) D. Kindergarten dp
    Codeforces Round #221 (Div. 1) B. Maximum Submatrix 2 dp排序
    hihoCoder Challenge 27 #1469 : 福字 dp
    Codeforces Beta Round #5 C. Longest Regular Bracket Sequence 括号序列 dp+栈
    Python id() 函数
    Python divmod() 函数
    Python any() 函数
    Python next() 函数
    Python slice() 函数
    Python3 hex() 函数
  • 原文地址:https://www.cnblogs.com/MartinLwx/p/11652903.html
Copyright © 2011-2022 走看看