【CCF CSP历年考试全题解 C++版】201912-3 化学方程式

【CCF CSP历年考试全题解 C++版】201912-3 化学方程式_第1张图片【CCF CSP历年考试全题解 C++版】201912-3 化学方程式_第2张图片【CCF CSP历年考试全题解 C++版】201912-3 化学方程式_第3张图片

#include 
#include 
using namespace std;

unordered_map record;
int num = 0;

bool recursion(string cur, bool add, int time);

int main() {
	int n;
	cin >> n;
	for (int i = 0; i < n; i++) {
		string cur;
		cin >> cur;
		int equal = 0;
		while (cur[equal] != '=') equal++;
		record.clear();
		num = 0;
		recursion(cur.substr(0, equal), true, 1);
		bool wrong = false;
		if (!recursion(cur.substr(equal + 1), false, 1) || num != 0) {
			cout << "N" << endl;
		}
		else {
			cout << "Y" << endl;
		}
	}
	return 0;
}

bool recursion(string cur, bool add, int time) {
	if (cur.empty()) return true;
	int plus = 0;
	while (plus < cur.size() && cur[plus] != '+') plus++;
	if (plus < cur.size()) {
		return recursion(cur.substr(0, plus), add, time) && recursion(cur.substr(plus+1), add, time);
	}
	else {
		if (cur[0] >= '0' && cur[0] <= '9') {
			int num_over = 1;
			int ratio = cur[0] - '0';
			while (cur[num_over] >= '0' && cur[num_over] <= '9') {
				ratio *= 10;
				ratio += cur[num_over++] - '0';
			}
			return recursion(cur.substr(num_over), add, time * ratio);
		}
		else if (cur[0] == '(') {
			int bracket_num = 1;
			int right = 1;
			while (bracket_num > 0) {
				if (cur[right] == '(') bracket_num++;
				else if (cur[right] == ')') bracket_num--;
				right++;
			}
			int temp = right;
			int ratio = 0;
			while (right < cur.size() && cur[right] >= '0' && cur[right] <= '9') {
				ratio *= 10;
				ratio += cur[right] - '0';
				right++;
			}
			if (ratio == 0) ratio = 1;
			return(recursion(cur.substr(1, temp - 2), add, time * ratio)) && recursion(cur.substr(right), add, time);
		}
		else {
			int lower = 1;
			while (lower < cur.size() && cur[lower] >= 'a' && cur[lower] <= 'z') lower++;
			string temp = cur.substr(0, lower);
			int ratio = 0;
			while (lower < cur.size() && cur[lower] >= '0' && cur[lower] <= '9') {
				ratio *= 10;
				ratio += cur[lower] - '0';
				lower++;
			}
			if (ratio == 0) ratio = 1;
			if (add) {
				record[temp] += time * ratio;
				num += time * ratio;
			}
			else {
				if (!record.count(temp)) return false;
				record[temp] -= time * ratio;
				num -= time * ratio;
				if (record[temp] < 0) return false;
			}
			return recursion(cur.substr(lower), add, time);
		}
	}
}

 

你可能感兴趣的:(CCF,CSP)