题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805526272000000
多项式相加,本意考察链表,可用数组偷懒
第一种做法卡了一个点,不过我也大致知道卡在那里了,但是想出更好的解决办法就没有改进
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 1010;
struct node
{
int x;
double z;
};
bool cmp(node &a, node &b)
{
return a.x > b.x;
}
vector<node> f1, f2, res;
int main()
{
int K;cin >> K;
node y;
while(K--)
{
cin >> y.x >> y.z;
f1.push_back(y);
}
cin >> K;
while(K--)
{
cin >> y.x >> y.z;
f2.push_back(y);
}
sort(f1.begin(), f1.end(), cmp);
sort(f2.begin(), f2.end(), cmp);
int a = 0,b = 0;
for(int i = 0; i <= max(f1.size(), f2.size()); i ++ )
{
if(a == f1.size())
{
if(b<f2.size()) res.push_back(f2[b]), b++;
continue;
}
if(b == f2.size())
{
if(a<f1.size()) res.push_back(f1[a]), a++;
continue;
}
if(f1[a].x>f2[b].x) res.push_back(f1[a]), a++;
else if(f1[a].x==f2[b].x)
{
node tmp;
tmp.x = f1[a].x;
tmp.z = f1[a].z+f2[b].z;
if(tmp.z!=0) res.push_back(tmp);
a++,b++;
}
else res.push_back(f2[b]), b++;
}
if(res.size() == 0)
{
cout<<"0";return 0;
}
sort(res.begin(), res.end(), cmp);
cout << res.size()<<" ";
for(int i = 0; i < res.size(); i ++ )
{
if(i == 0) printf("%d %.1lf",res[i].x,res[i].z);
else printf(" %d %.1lf",res[i].x,res[i].z);
}
return 0;
}
代码写的很臭,总结了几个坑点
- 相抵消的情况,比如
1 0 -1
1 0 1
output
0
- 它的输入并不一定是合并完的多相式
2 2 0.2 2 -0.1
3 3 7.8 2 6 1 9
output
3 3 7.8 2 6.1 1 9.0
第一个代码应该是卡在了第二个坑点
ac代码:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
double f[N];
int main()
{
int cnt = -1;
for(int j = 0; j < 2; j ++ )
{
int k; cin >> k;
int x;
double y;
for(int i = 0; i < k; i ++ )
{
cin >> x >> y;
f[x] += y;
cnt = max(cnt, x);
}
}
int res = 0;
for(int i = 0; i <= cnt; i ++ )
if(f[i]!=0) res++;
cout << res;
for(int i = cnt; i >= 0; i -- )
if(f[i]!=0) printf(" %d %.1lf",i,f[i]);
return 0;
}
欢迎大家指正~