跳到正文

剪贴板

剪贴板 ngr8uowc

SClan_Official
原文
剪贴板信息

剪贴板信息

发布
收录
更新

upd on 2026/08/18: !更新了代码。下面是新版代码:

方法一:

C++
#include <stack>
#include <cstdio>
#include <string>
#include <cctype>
#include <sstream>
#include <iostream>
#include <algorithm>

using namespace std;

int youxian[255];

class myc
{
public:
	char type;
	int num;
	char op;
} expr[105], houexp[105];

bool isnum(const string& x)
{
	return isdigit(x[0]) || x.size() > 1 && isdigit(x[1]);
}

int getexp(stringstream& ss)
{
	int len = 0;
	string str;
	while (ss >> str)
	{
		if (isnum(str)) expr[++len] = { 'N', stoi(str), '\0' };
		else expr[++len] = { 'C', -114514, str[0] };
	}
	return len;
}

int zhong2hou(int len) //中缀转后缀
{
	youxian['('] = 1;
	youxian['+'] = youxian['-'] = 2;
	youxian['*'] = youxian['/'] = 3;
	youxian['^'] = 4;
	stack<char> oper;
	myc now;
	int cur = 0;
	for (int i = 1; i <= len; i++)
	{
		now = expr[i];
		if (now.type == 'N') //数字
		{
			houexp[++cur] = now;
			continue;
		}
		if (now.op == '(') oper.push(now.op);
		else if (now.op == ')')
		{
			while (oper.top() != '(') //连续出栈
			{
				houexp[++cur] = { 'C', -114514, oper.top() };
				oper.pop();
			}
			oper.pop(); //出栈'('
		}
		else if (oper.empty() || youxian[now.op] > youxian[oper.top()])
        {
            if((now.op == '+' || now.op == '-') && (i == 1 || expr[i-1].type == 'C' && expr[i-1].op != ')')) oper.push(now.op == '+' ? '=' : '_');
            else oper.push(now.op);
        }
		else if (now.op == '^')
		{
			while (!oper.empty() && youxian[oper.top()] > youxian[now.op]) //连续出栈
			{
				houexp[++cur] = { 'C', -114514, oper.top() };
				oper.pop();
			}
			oper.push(now.op);
		}
		else
		{
			while (!oper.empty() && youxian[oper.top()] >= youxian[now.op]) //连续出栈
			{
				houexp[++cur] = { 'C', -114514, oper.top() };
				oper.pop();
			}
			oper.push(now.op);
		}
	}
	while (!oper.empty())
	{
		houexp[++cur] = { 'C', -114514, oper.top() };
		oper.pop();
	}
	return cur;
}

int qpow(int x, int y)
{
	//萌新第一次写循环快速幂,请多关照QwQ
	int ans = 1, qwq = x;
	while (y)
	{
		if (y & 1) ans *= qwq;
		qwq *= qwq;
		y /= 2;
	}
	return ans;
}

int calc(int len)
{
	stack<int> num;
	myc now;
	for (int i = 1; i <= len; i++)
	{
		now = houexp[i];
		if (now.type == 'N') num.push(now.num);
		else
		{
			char ch = now.op;
			int x = num.top(); num.pop();
			int y;
			switch (ch)
			{
			case '+': y = num.top(); num.pop(); num.push(x + y); break;
			case '-': y = num.top(); num.pop(); num.push(y - x); break;
			case '*': y = num.top(); num.pop(); num.push(x * y); break;
			case '/': y = num.top(); num.pop(); num.push(y / x); break;
			case '^': y = num.top(); num.pop(); num.push(qpow(y, x)); break;
            case '=': num.push(x); break;
            case '_': num.push(-x); break;
			}
		}
	}
	return num.top();
}

int main()
{
	string str;
	getline(cin, str);
	int lkh = 0, rkh = 0, kh = 0;
	for (char ch : str)
	{
		if (ch == '(') kh++;
		if (ch == ')') kh--;
		if (kh < 0)
		{
			lkh += -kh;
			kh = 0;
		}
	}
	if (kh < 0)
	{
		lkh += -kh;
		kh = 0;
	}
	if (kh > 0)
	{
		rkh = kh;
		kh = 0;
	}
	str = string(lkh, '(') + str + string(rkh, ')');
	stringstream ss;
	//加空格,好处理。
	//如:"(2+2)^(1+1)" 变为 " ( 2 + 2 )  ^  ( 1 + 1 ) "
	for (int i = 0; i < str.size(); i++)
	{
		char ch = str[i];
		bool isoperator = false;
		isoperator |= (ch == '+' || ch == '-') && i != 0 && (isdigit(str[i - 1]) || str[i - 1] == ')');
		isoperator |= ch == '*' || ch == '/' || ch == '^' || ch == '(' || ch == ')';
		if (isoperator) ss << ' ' << ch << ' ';
		else ss << ch;
	}
	int len = getexp(ss);
	/*for (int i = 1; i <= len; i++)
	{
		printf("{%c, %d, %c}\n", expr[i].type, expr[i].num, expr[i].op);
	}*/
	int reallen = zhong2hou(len);
	/*printf("QwQ\n");
	for (int i = 1; i <= reallen; i++)
	{
		printf("{%c, %d, %c}\n", houexp[i].type, houexp[i].num, houexp[i].op);
	}*/
	//cout << hou.str() << endl;
	printf("%d\n", calc(reallen));
	return 0;
}

方法二:

C++
#include <cctype>
#include <string>
#include <cctype>
#include <iostream>
using namespace std;

class node
{
public:
	char type;
	int num;
	char op;
	node* l, * r;
};

void gettree(node* root, string str)
{
    if(str.empty())
    {
        printf("huh? plz report to SClan_Official or lihaochen123. Will cuz RE."); fflush(stdout);
    }
	int minn = 2147483647;
	int pt = 0;
	for (char ch : str)
	{
		if (ch == '(') pt++;
		else if (ch == ')') pt--;
		else if (pt < minn) minn = pt;
	}
	if (minn) gettree(root, str.substr(minn, str.size() - 2 * minn));
	else
	{
		int khr = 0;
		for (int i = str.size() - 1; i >= 0; i--)
		{
			if (str[i] == ')') khr++;
			if (str[i] == '(') khr--;
			if (khr == 0 && (str[i] == '+' || str[i] == '-'))
			{
				root->type = 'O';
				root->op = str[i];
				if(i) gettree(root->l = new node, str.substr(0, i));
                else root->l = new node{'N', 0, 114, nullptr, nullptr};
				if(i < str.size() - 1) gettree(root->r = new node, str.substr(i + 1));
                else root->r = new node{'N', 0, 114, nullptr, nullptr};
				return;
			}
		}
		for (int i = str.size() - 1; i >= 0; i--)
		{
			if (str[i] == ')') khr++;
			if (str[i] == '(') khr--;
			if (khr == 0 && (str[i] == '*' || str[i] == '/'))
			{
				root->type = 'O';
				root->op = str[i];
				gettree(root->l = new node, str.substr(0, i));
				gettree(root->r = new node, str.substr(i + 1));
				return;
			}
		}
		for (int i = 0; i < str.size(); i++)
		{
			if (str[i] == '(') khr++;
			if (str[i] == ')') khr--;
			if (khr == 0 && str[i] == '^')
			{
				root->type = 'O';
				root->op = str[i];
				gettree(root->l = new node, str.substr(0, i));
				gettree(root->r = new node, str.substr(i + 1));
				return;
			}
		}
		root->type = 'N';
		root->num = stoi(str);
		root->l = root->r = nullptr;
	}
}

static int qpow(int x, int y)
{
	if (y == 0) return 1;
	if (y == 1) return x;
	int g = qpow(x, y / 2);
	return g * g * ((y & 1) ? x : 1);
}

int calc(node* root)
{
	if (root->type == 'N') return root->num;
	switch (root->op)
	{
	case '+': return calc(root->l) + calc(root->r); break;
	case '-': return calc(root->l) - calc(root->r); break;
	case '*': return calc(root->l) * calc(root->r); break;
	case '/': return calc(root->l) / calc(root->r); break;
	case '^': return qpow(calc(root->l), calc(root->r)); break;
	}
}

int exp_tree(string str)
{
	int lkh = 0, rkh = 0, kh = 0;
	for (char ch : str)
	{
		if (ch == '(') kh++;
		if (ch == ')') kh--;
		if (kh < 0)
		{
			lkh += -kh;
			kh = 0;
		}
	}
	if (kh < 0)
	{
		lkh += -kh;
		kh = 0;
	}
	if (kh > 0)
	{
		rkh = kh;
		kh = 0;
	}
	str = string(lkh, '(') + str + string(rkh, ')');
	int pos;
	while ((pos = str.find("()")) != string::npos) str.erase(pos, 2);
	//cout << str << endl;
	node* root = new node;
	gettree(root, str);
	return calc(root);
}

int main()
{
	string str;
	cin >> str;
	printf("%d\n", exp_tree(str));
	return 0;
}

旧版代码(无法正确处理一元正负号)

方法一:

C++
#include <stack>
#include <cstdio>
#include <string>
#include <cctype>
#include <sstream>
#include <iostream>
#include <algorithm>

using namespace std;

int youxian[255];

class myc
{
public:
	char type;
	int num;
	char op;
} expr[105], houexp[105];

bool isnum(const string& x)
{
	return isdigit(x[0]) || x.size() > 1 && isdigit(x[1]);
}

int getexp(stringstream& ss)
{
	int len = 0;
	string str;
	while (ss >> str)
	{
		if (isnum(str)) expr[++len] = { 'N', stoi(str), '\0' };
		else expr[++len] = { 'C', -114514, str[0] };
	}
	return len;
}

int zhong2hou(int len) //中缀转后缀
{
	youxian['('] = 1;
	youxian['+'] = youxian['-'] = 2;
	youxian['*'] = youxian['/'] = 3;
	youxian['^'] = 4;
	stack<char> oper;
	myc now;
	int cur = 0;
	for (int i = 1; i <= len; i++)
	{
		now = expr[i];
		if (now.type == 'N') //数字
		{
			houexp[++cur] = now;
			continue;
		}
		if (now.op == '(') oper.push(now.op);
		else if (now.op == ')')
		{
			while (oper.top() != '(') //连续出栈
			{
				houexp[++cur] = { 'C', -114514, oper.top() };
				oper.pop();
			}
			oper.pop(); //出栈'('
		}
		else if (oper.empty() || youxian[now.op] > youxian[oper.top()]) oper.push(now.op);
		else if (now.op == '^')
		{
			while (!oper.empty() && youxian[oper.top()] > youxian[now.op]) //连续出栈
			{
				houexp[++cur] = { 'C', -114514, oper.top() };
				oper.pop();
			}
			oper.push(now.op);
		}
		else
		{
			while (!oper.empty() && youxian[oper.top()] >= youxian[now.op]) //连续出栈
			{
				houexp[++cur] = { 'C', -114514, oper.top() };
				oper.pop();
			}
			oper.push(now.op);
		}
	}
	while (!oper.empty())
	{
		houexp[++cur] = { 'C', -114514, oper.top() };
		oper.pop();
	}
	return cur;
}

int qpow(int x, int y)
{
	//萌新第一次写循环快速幂,请多关照QwQ
	int ans = 1, qwq = x;
	while (y)
	{
		if (y & 1) ans *= qwq;
		qwq *= qwq;
		y /= 2;
	}
	return ans;
}

int calc(int len)
{
	stack<int> num;
	myc now;
	for (int i = 1; i <= len; i++)
	{
		now = houexp[i];
		if (now.type == 'N') num.push(now.num);
		else
		{
			char ch = now.op;
			int x = num.top(); num.pop();
			int y = num.top(); num.pop();
			switch (ch)
			{
			case '+': num.push(x + y); break;
			case '-': num.push(y - x); break;
			case '*': num.push(x * y); break;
			case '/': num.push(y / x); break;
			case '^': num.push(qpow(y, x)); break;
			}
		}
	}
	return num.top();
}

int main()
{
	string str;
	getline(cin, str);
	int lkh = 0, rkh = 0, kh = 0;
	for (char ch : str)
	{
		if (ch == '(') kh++;
		if (ch == ')') kh--;
		if (kh < 0)
		{
			lkh += -kh;
			kh = 0;
		}
	}
	if (kh < 0)
	{
		lkh += -kh;
		kh = 0;
	}
	if (kh > 0)
	{
		rkh = kh;
		kh = 0;
	}
	str = string(lkh, '(') + str + string(rkh, ')');
	stringstream ss;
	//加空格,好处理。
	//如:"(2+2)^(1+1)" 变为 " ( 2 + 2 )  ^  ( 1 + 1 ) "
	for (int i = 0; i < str.size(); i++)
	{
		char ch = str[i];
		bool isoperator = false;
		isoperator |= (ch == '+' || ch == '-') && i != 0 && (isdigit(str[i - 1]) || str[i - 1] == ')');
		isoperator |= ch == '*' || ch == '/' || ch == '^' || ch == '(' || ch == ')';
		if (isoperator) ss << ' ' << ch << ' ';
		else ss << ch;
	}
	int len = getexp(ss);
	/*for (int i = 1; i <= len; i++)
	{
		printf("{%c, %d, %c}\n", expr[i].type, expr[i].num, expr[i].op);
	}*/
	int reallen = zhong2hou(len);
	/*printf("QwQ\n");
	for (int i = 1; i <= reallen; i++)
	{
		printf("{%c, %d, %c}\n", houexp[i].type, houexp[i].num, houexp[i].op);
	}*/
	//cout << hou.str() << endl;
	printf("%d\n", calc(reallen));
	return 0;
}

方法二:

C++
#include <cctype>
#include <string>
#include <cctype>
#include <iostream>
using namespace std;

class node
{
public:
	char type;
	int num;
	char op;
	node* l, * r;
};

void gettree(node* root, string str)
{
	int minn = 2147483647;
	int pt = 0;
	for (char ch : str)
	{
		if (ch == '(') pt++;
		else if (ch == ')') pt--;
		else if (pt < minn) minn = pt;
	}
	if (minn) gettree(root, str.substr(minn, str.size() - 2 * minn));
	else
	{
		int khr = 0;
		for (int i = str.size() - 1; i >= 0; i--)
		{
			if (str[i] == ')') khr++;
			if (str[i] == '(') khr--;
			if (khr == 0 && (str[i] == '+' || str[i] == '-') && i > 0 && (isdigit(str[i - 1]) || str[i-1] == ')'))
			{
				root->type = 'O';
				root->op = str[i];
				gettree(root->l = new node, str.substr(0, i));
				gettree(root->r = new node, str.substr(i + 1));
				return;
			}
		}
		for (int i = str.size() - 1; i >= 0; i--)
		{
			if (str[i] == ')') khr++;
			if (str[i] == '(') khr--;
			if (khr == 0 && (str[i] == '*' || str[i] == '/'))
			{
				root->type = 'O';
				root->op = str[i];
				gettree(root->l = new node, str.substr(0, i));
				gettree(root->r = new node, str.substr(i + 1));
				return;
			}
		}
		for (int i = 0; i < str.size(); i++)
		{
			if (str[i] == '(') khr++;
			if (str[i] == ')') khr--;
			if (khr == 0 && str[i] == '^')
			{
				root->type = 'O';
				root->op = str[i];
				gettree(root->l = new node, str.substr(0, i));
				gettree(root->r = new node, str.substr(i + 1));
				return;
			}
		}
		root->type = 'N';
		root->num = stoi(str);
		root->l = root->r = nullptr;
	}
}

static int qpow(int x, int y)
{
	if (y == 0) return 1;
	if (y == 1) return x;
	int g = qpow(x, y / 2);
	return g * g * ((y & 1) ? x : 1);
}

int calc(node* root)
{
	if (root->type == 'N') return root->num;
	switch (root->op)
	{
	case '+': return calc(root->l) + calc(root->r); break;
	case '-': return calc(root->l) - calc(root->r); break;
	case '*': return calc(root->l) * calc(root->r); break;
	case '/': return calc(root->l) / calc(root->r); break;
	case '^': return qpow(calc(root->l), calc(root->r)); break;
	}
}

int exp_tree(string str)
{
	int lkh = 0, rkh = 0, kh = 0;
	for (char ch : str)
	{
		if (ch == '(') kh++;
		if (ch == ')') kh--;
		if (kh < 0)
		{
			lkh += -kh;
			kh = 0;
		}
	}
	if (kh < 0)
	{
		lkh += -kh;
		kh = 0;
	}
	if (kh > 0)
	{
		rkh = kh;
		kh = 0;
	}
	str = string(lkh, '(') + str + string(rkh, ')');
	int pos;
	while ((pos = str.find("()")) != string::npos) str.erase(pos, 2);
	//cout << str << endl;
	node* root = new node;
	gettree(root, str);
	return calc(root);
}

int main()
{
	string str;
	cin >> str;
	printf("%d\n", exp_tree(str));
	return 0;
}