您的位置:首页 > 其它

一元多项式的乘法与加法运算 【STL-map哈希-map反向迭代器遍历 + 零多项式】

2015-09-06 10:54 381 查看
设计函数分别求两个一元多项式的乘积与和。

输入格式:

输入分2行,每行分别先给出多项式非零项的个数,再以指数递降方式输入一个多项式非零项系数和指数(绝对值均为不超过1000的整数)。数字间以空格分隔。

输出格式:

输出分2行,分别以指数递降方式输出乘积多项式以及和多项式非零项的系数和指数。数字间以空格分隔,但结尾不能有多余空格。

输入样例:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1

输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0


数据测试补充:[/code]
4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1输出:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

2 1 2 1 0
2 1 2 -1 0
输出:

1 4 -1 0
2 2

2 -1000 1000 1000 0
2 1000 1000 -1000 0
输出:

-1000000 2000 2000000 1000 -1000000 0
0 0

0
1 999 1000
输出:

0 0
999 1000

上面的丝足测试数据都过了的话,代码应该就能过了。


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <map>
#include <algorithm>

using namespace std;

int n, m;
struct node
{
int x, z;
}a[200], b[200];

int main()
{
int i, j;
scanf("%d", &n);
for(i=0; i<n; i++){
scanf("%d %d", &a[i].x, &a[i].z );
}
scanf("%d", &m);
for(i=0; i<m; i++){
scanf("%d %d", &b[i].x, &b[i].z );
}
map<int,int>q;
int cur;
for(i=0; i<n; i++){
for(j=0; j<m; j++){
cur=a[i].z+b[j].z;
q[cur]+=(a[i].x*b[j].x);
}
}
int cnt=0;
bool flag=false;
map<int, int>::reverse_iterator it=q.rbegin();
for(it; it!=q.rend(); it++){
if(flag==false){
if(it->second==0) continue;
else{
flag=true;
printf("%d %d", it->second, it->first); cnt++;
}
}else{
if(it->second==0) continue;
else printf(" %d %d", it->second, it->first); cnt++;
}
}
if(cnt==0){
printf("0 0");
}printf("\n");

map<int, int>h;
for(i=0; i<n; i++){
h[a[i].z]+=a[i].x;
}
for(j=0; j<m; j++){
h[b[j].z]+=b[j].x;
}
flag=false;
it=h.rbegin(); cnt=0;
for(it; it!=h.rend(); it++){
if(flag==false){
if(it->second==0) continue;
else{
flag=true;
printf("%d %d", it->second, it->first); cnt++;
}
}else{
if(it->second==0) continue;
else printf(" %d %d", it->second, it->first); cnt++;
}
}
if(cnt==0){
printf("0 0");//没有合法输出的情况下,就输出0 0;
}printf("\n");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: