多项式加法
来源:互联网 发布:录像配音软件 编辑:程序博客网 时间:2024/06/05 12:39
题目地址:http://dsalgo.openjudge.cn/huawen02/2/
本来打算直接用数组直接模拟,后来发现越写越复杂。
最后打算数据用一个单向链表来存。
1. 定义一个投节点pHead。
2. 每次新增加的节点存在pHead节点后。
3. 对链表的元素进行排序,只改节点中的值而不是移动具体节点。
4. 注意第一行可能存在 (如3 5 6 2 6 5 9 -8) 这样的数据,因为开始并没有考虑到第一行会存在相同幂指数,导致一直WA了。
国庆还在刷题 也是没谁了
#include <cstdio>#include <algorithm>#include <cstring>#include <iostream>using namespace std;typedef struct LNode{ int xishu; int ming; struct LNode * next;}LNode;void insertNode(LNode* pHead,int xishu,int ming){ LNode * node = new LNode(); node->xishu = xishu; node->ming = ming; node->next = pHead->next; pHead->next = node;}bool findNode(LNode* pHead,int xishu,int ming){ for(LNode *node=pHead->next; node!=NULL;node=node->next) { if(node->ming == ming) { node->xishu += xishu; return true; } } return false;}void sortNode(LNode* pHead){ for(LNode* l1=pHead->next; l1 != NULL; l1=l1->next) { for(LNode* l2=l1; l2 != NULL; l2=l2->next) { if(l1->ming < l2->ming) { int linshi_xishu = l1->xishu; int linshi_ming = l1->ming; l1->xishu = l2->xishu; l1->ming = l2->ming; l2->xishu = linshi_xishu; l2->ming = linshi_ming; } } }}int main(){ int n; while(~scanf("%d",&n)) { while(n--) { LNode *l1 = new LNode(); l1->next=NULL; int t=2; while(t--) { while(1) { int x,y; scanf("%d%d",&x,&y); if(y<0) break; if(!findNode(l1,x,y)) insertNode(l1,x,y); } } sortNode(l1); bool flag=true; for(LNode* l=l1->next; l!=NULL; l=l->next) { if(l->xishu == 0) continue; if(flag) { printf("[ %d %d ]",l->xishu,l->ming); flag = false; } else printf(" [ %d %d ]",l->xishu,l->ming); } printf("\n"); while(l1) { LNode * q = l1; l1 = l1->next; delete q; } } } return 0;}
阅读全文
0 0