Submission #1350337

#TimeUsernameProblemLanguageResultExecution timeMemory
1350337vjudge1Slon (COCI15_slon)C++20
120 / 120
2 ms1348 KiB
#include <iostream>
#include <vector>
using namespace std;
#define int long long
int M, P;
string og;
const int N = 1e5 + 100;
int nxt[N], prv[N];
pair<int, int> mul(pair<int, int> a, pair<int, int> b)
{
	return {(1ll * a.first * b.second + 1ll * a.second * b.first) % M, (1ll * a.second * b.second) % M};
}
pair<int, int> add(pair<int, int> a, pair<int, int> b)
{
	return {(a.first + b.first) % M, (a.second + b.second) % M};
}
pair<int, int> sub(pair<int, int> a, pair<int, int> b)
{
	return {(a.first + M - b.first) % M, (a.second + M - b.second) % M};
}
pair<int, int> solve(int l, int r)
{
	// cout << "at " << l << ' ' << r << endl;
	vector<pair<int, int>> opr; // operand
	vector<char> op;			// operation
	for (int i = l; i <= r; i++)
	{
		int p = opr.size();
		if (og[i] == '(')
		{
			opr.push_back(solve(i + 1, nxt[i] - 1));
			i = nxt[i];
		}
		else if ('0' <= og[i] and og[i] <= '9')
		{
			// digit
			int j = i;
			int num = 0;
			while (j <= r and '0' <= og[j] and og[j] <= '9')
			{
				num = ((num * 10) + (og[j] - '0')) % M;
				j++;
			}
			opr.push_back({0, num});
			i = j - 1;
		}
		else if (og[i] == 'x')
		{
			opr.push_back({1, 0});
		}
		else
		{
			op.push_back(og[i]);
		}
		if (op.size() > 0 and op.back() == '*' and og[i] != '*' and opr.size() > p)
		{
			auto cur = opr.back();
			opr.pop_back();
			opr.back() = mul(opr.back(), cur);
			op.pop_back();
		}
	}
	pair<int, int> qg = {0, 0};
	// cout<<"numbers"<<endl;
	// for(auto it:opr)cout<<it.first<<' '<<it.second<<endl;
	// cout<<"Operations"<<endl;
	// for(auto x:op)
	// {
	// 	cout<<x<<' ';
	// }
	// cout<<endl;
	qg = opr[0];
	for (int i = 1; i < opr.size(); i++)
	{
		if (op[i - 1] == '+')
		{
			qg = add(qg, opr[i]);
		}
		else
		{
			qg = sub(qg, opr[i]);
		}
	}
	return qg;
}
main()
{
	cin >> og;
	vector<int> lst;
	for (int i = og.size() - 1; i >= 0; i--)
	{
		if (og[i] == ')')
		{
			lst.push_back(i);
		}
		else if (og[i] == '(')
		{
			nxt[i] = lst.back();
			lst.pop_back();
		}
	}
	cin >> P >> M;
	pair<int, int> eq = solve(0, og.size() - 1);
	// x*eq.first + eq.second == P (mod M)
	// x*eq.first
	// cout << eq.first << ' ' << eq.second << endl;
	P = ((P - eq.second) % M + M) % M;
	for (int x = 0; x < M; x++)
	{
		if (1ll * x * eq.first % M == P)
		{
			cout << x << endl;
			break;
		}
	}
}

Compilation message (stderr)

slon.cpp:86:1: warning: ISO C++ forbids declaration of 'main' with no type [-Wreturn-type]
   86 | main()
      | ^~~~
#Verdict Execution timeMemoryGrader output
Fetching results...