题目链接
这题占个坑吧。。。我用了两种思路,一种将保存结果的数组初始化为 0,把乘积加上去,顺便记录下最后一个指数的值。用两次 2000 次 for 循环过滤掉 0 值以及输出答案,这个代码过了,但是后期测试的时候,有些测试用例会多出来空格,有些则格式不对。。但是过了。。。
代码如下
#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
double A[1001], B[1001];
int ExpA[11], ExpB[11];
double Result[2001];
double coe;
int Acounts, Bcounts, exp, EndIndex = 0;
// 初始化多项式
for (int i = 0; i < 1001; i++) {
A[i] = B[i] = 0;
}
for (int i = 0; i < 2001; i++) {
Result[i] = 0;
}
cin >> Acounts;
for (int i = 0; i < Acounts; i++) {
cin >> exp >> coe;
ExpA[i] = exp;
A[exp] = coe;
}
cin >> Bcounts;
for (int i = 0; i < Bcounts; i++) {
cin >> exp >> coe;
ExpB[i] = exp;
B[exp] = coe;
}
for (int i = 0; i < Acounts; i++) {
for (int j = 0; j < Bcounts; j++) {
//cout << "=====================" << endl;
//cout << "Result[ExpA[i] + ExpB[j]] = " << Result[ExpA[i] + ExpB[j]] << endl;
Result[ExpA[i] + ExpB[j]] += A[ExpA[i]] * B[ExpB[j]];
//cout << "A[ExpA[i]] * B[ExpB[j]] = " << A[ExpA[i]] * B[ExpB[j]] << endl;
//cout << "Result[ExpA[i] + ExpB[j]] = " << Result[ExpA[i] + ExpB[j]] << endl;
//cout << "=====================" << endl;
EndIndex = ExpA[i] + ExpB[j];
}
}
int AllResCount = 0;
for (int i = 2000; i >= 0; i--) {
if (Result[i] != 0) {
AllResCount++;
}
}
cout << AllResCount << " ";
for (int i = 2000; i >= 0; i--) {
if (Result[i] != 0) {
printf("%d %.1f", i, Result[i]);
if (i != EndIndex)
cout << " ";
}
}
return 0;
}
另外一种思路是将保存结果的数组初始化为 -1 ,边计算多项式边记录非零多项式的项数,最后输出答案,测试点 0 答案错误。。。我百度了好久,好多帖子指出是跟系数为 0 有关,我自己做了几个系数为 0 测试用例,测试结果和我在纸上计算的答案一致,包括格式也正确,我实在弄不懂了。。。代码如下:
#include<iostream>
#include<stdio.h>
using namespace std;
int main() {
double A[1001], B[1001];
int ExpA[11], ExpB[11], ItemIndex[10];
double Result[2001];
double coe;
int Acounts, Bcounts, exp, ResCounts = 0;
// 初始化多项式
for (int i = 0; i < 1001; i++) {
A[i] = B[i] = -1;
}
for (int i = 0; i < 2001; i++) {
Result[i] = -1;
}
cin >> Acounts;
for (int i = 0; i < Acounts; i++) {
cin >> exp >> coe;
ExpA[i] = exp;
A[exp] = coe;
}
cin >> Bcounts;
for (int i = 0; i < Bcounts; i++) {
cin >> exp >> coe;
ExpB[i] = exp;
B[exp] = coe;
}
int indexCount = 0;
for (int i = 0; i < Acounts; i++) {
for (int j = 0; j < Bcounts; j++) {
if (Result[ExpA[i] + ExpB[j]] == -1) {
Result[ExpA[i] + ExpB[j]] = A[ExpA[i]] * B[ExpB[j]];
if (Result[ExpA[i] + ExpB[j]] != 0) {
ResCounts++;
}
}
else {
if (Result[ExpA[i] + ExpB[j]] == 0 && A[ExpA[i]] * B[ExpB[j]] != 0)
ResCounts++;
Result[ExpA[i] + ExpB[j]] += A[ExpA[i]] * B[ExpB[j]];
}
}
}
cout << ResCounts << " ";
for (int i = 2000; i >= 0; i--) {
if (Result[i] != -1 && Result[i] != 0) {
ResCounts--;
//cout << "----" << ResCounts << "----" << endl;
printf("%d %.1f", i, Result[i]);
if (ResCounts != 0)
printf(" ");
}
}
return 0;
}
希望有大佬可以指出错误QAQ
原文地址:https://www.cnblogs.com/Breathmint/p/10283356.html
时间: 2024-11-08 13:30:39