a718中等一次式解析與有號向下整除
CPE:A DP Problem (UVa 1200)
把每側歸納成 Ax+B,再分類求解。
解題思路
以項為單位掃描,每項先讀連接符號,再讀可省略的數字,最後判斷是否接 x。含 x 的項加入係數 A,其餘加入常數 B;單獨 x 的係數是 1,而 0x 的係數確實是 0。左右各得到一對係數。
移項後有 (AL−AR)x=BR−BL。係數為零時,常數也為零輸出 IDENTITY,否則 IMPOSSIBLE。唯一解需向下取整;Python // 已符合,C++ 除法朝零截斷,餘數非零且分子分母異號時還要減 1。依開頭 t 讀取方程式,每題一行。
Step-by-step animation
示意:2x+3=0
步驟 1 / 3
解析左側
2x 加入係數,3 加入常數。
2x
+3
- AL
- 2
- BL
- 3
#include <iostream>
#include <string>
#include <utility>
#include <cctype>
using namespace std;
pair<long long, long long> parse(const string &s) {
long long a = 0, b = 0;
size_t i = 0;
while (i < s.size()) {
int sign = 1;
if (s[i] == '+' || s[i] == '-')
sign = s[i++] == '-' ? -1 : 1;
long long v = 0;
bool has = false;
while (i < s.size() && isdigit(s[i])) {
has = true;
v = v * 10 + s[i++] - '0';
}
if (i < s.size() && s[i] == 'x') {
++i;
a += sign * (has ? v : 1);
} else
b += sign * v;
}
return {a, b};
}
int main() {
int t;
cin >> t;
while (t--) {
string s;
cin >> s;
auto pos = s.find('=');
auto l = parse(s.substr(0, pos)), r = parse(s.substr(pos + 1));
long long a = l.first - r.first, b = r.second - l.second;
if (!a)
cout << (b ? "IMPOSSIBLE" : "IDENTITY") << '\n';
else {
long long q = b / a;
if (b % a && ((b < 0) != (a < 0)))
--q;
cout << q << '\n';
}
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。