题解
2026-01-12 09:08:54
发布于:浙江
1阅读
0回复
0点赞
题目解析
- 输入输出:输入为一个整数n和n+1个整数,表示多项式的次数及各项系数。输出为格式化的多项式字符串。
- 数据范围:n的范围是0到100,系数范围是-100到100。
- 复杂度要求:线性时间复杂度即可满足要求。
- 算法知识点:字符串处理、条件判断、格式化输出
思路解析
- 读取输入的多项式次数n和各项系数,存储在数组a中。
- 构建结果字符串ans,遍历每个系数:
- 根据系数值决定符号(正用+,负用-)。
- 处理系数绝对值,若为1且不是常数项则省略。
- 处理x的指数部分,根据指数大小添加相应的格式。
- 最后处理特殊情况(如结果字符串为空时输出"0")。
完整代码
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
const int ZERO = 0;
const int MOD = 1e9 + 7;
const int N = 5e5 + 10;
void solve() {
int n;
cin >> n;
vector<int> a(n + 1);
for (int i = 0; i <= n; i++) cin >> a[i];
string ans = "";
for (int i = 0; i <= n; i++) {
string tp = "";
// 根据系数值决定符号
(a[i]) and (tp = (a[i] > 0 and ans.size())?(tp + "+"):(a[i] < 0)?(tp + "-"):(tp),tp = (abs(a[i]) != 1 or i == n)?(tp + to_string(abs(a[i]))):(tp),tp += (i == n - 1)?("x"):(i != n)?("x^" + to_string(n - i)):"",1);
ans += tp;
}
cout << (ans.size()?ans:"0") << endl;
}
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int T = 1;
//cin >> T;
while (T--) solve();
return 0;
}
这里空空如也

有帮助,赞一个