Petya wrote a programme on C++ that calculated a very interesting function f(n). Petya ran the program with a certain value of n and went to the kitchen to have some tea. The history has no records concerning how long the program had been working. By the time Petya returned, it had completed the calculations and had the result. However while Petya was drinking tea, a sly virus managed to destroy the
input file so that Petya can't figure out for which value of n the program was run. Help Petya, carry out the inverse function!
Mostly, the program consists of a function in C++ with the following simplified syntax:
The whitespaces in a operatorSequence are optional.
Thus, we have a function, in which body there are two kinds of operators. There is the operator "return arithmExpr;" that returns the value of the expression as the value of the function, and there is the conditional operator "if (logicalExpr) return arithmExpr;" that returns the value of the arithmetical expression when and only when the logical expression is true. Guaranteed that no other constructions of C++ language — cycles, assignment operators, nested conditional operators etc, and other variables except the n parameter are used in the function. All the constants are integers in the interval [0..32767].
The operators are performed sequentially. After the function has returned a value other operators in the sequence are not performed. Arithmetical expressions are performed taking into consideration the standard priority of the operations. It means that first all the products that are part of the sum are calculated. During the calculation of the products the operations of multiplying and division are performed from the left to the right. Then the summands are summed, and the addition and the subtraction are also performed from the left to the right. Operations ">" (more), "<" (less) and "==" (equals) also have standard meanings.
Now you've got to pay close attention! The program is compiled with the help of 15-bit Berland C++ compiler invented by a Berland company BerSoft, that's why arithmetical operations are performed in a non-standard way. Addition, subtraction and multiplication are performed modulo 32768 (if the result of subtraction is negative, then 32768 is added to it until the number belongs to the interval [0..32767]). Division "/" is a usual integer division where the remainder is omitted.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Guaranteed that for all values of n from 0 to 32767 the given function is performed correctly. That means that:
Division by 0 never occures.
When performing a function for the value n = N recursive calls of the function f may occur only for the parameter value of 0, 1, ..., N - 1. Consequently, the program never has an infinite recursion.
As the result of the sequence of the operators, the function always returns a value.
We have to mention that due to all the limitations the value returned by the function f is independent from either global variables or the order of performing the calculations of arithmetical expressions as part of the logical one, or from anything else except the value of n parameter. That's why the f function can be regarded as a function in its mathematical sense, i.e. as a unique correspondence between any value of n from the interval [0..32767] and a value of f(n) from the same interval.
Given the value of f(n), and you should find n. If the suitable n value is not unique, you should find the maximal one (from the interval [0..32767]).
Input
The first line has an integer f(n) from the interval [0..32767]. The next lines have the description of the function f. In the description can be found extra spaces and line breaks (see the examples) which, of course, can’t break key words int, if, return and numbers. The size of input data can’t exceed 100 bytes.
Output
Output a single number — the answer to the problem. If there’s no answer, output "-1" (without quotes).
Examples
Input
17
int f(int n)
{
if (n < 100) return 17;
if (n > 99) return 27;
}
Output
99
Input
13
int f(int n)
{
if (n == 0) return 0;
return f(n - 1) + 1;
}
Output
13
Input
144
int f(int n)
{
if (n == 0) return 0;
if (n == 1) return n;
return f(n - 1) + f(n - 2);
}
Output
24588
To solve this problem, we need to determine the input value ( n ) such that a given function ( f(n) ) returns a specific value. The function is written in a simplified C++ that uses 15-bit arithmetic operations and may involve recursion such that each recursive call ensures a smaller input value. Our task is to find the maximum ( n ) (if multiple exist) for which the function returns the target value.
Approach
Parse the Input Function: Extract and process the function's code between the braces. This involves handling HTML entities (like < and >) and splitting the code into individual operators.
Parse Operators into Nodes: Each operator (either a return statement or a conditional return) is parsed into an abstract syntax tree (AST) to handle arithmetic expressions and logical conditions.
Precompute Function Values: Compute the value of ( f(n) ) for all ( n ) from 0 to 32767. This is done by iterating over possible ( n ) values, evaluating each operator in sequence until a return statement is encountered, and storing results in an array ( \text{F} ).
Find Maximum Valid ( n ): Search the precomputed array ( \text{F} ) from the highest to lowest ( n ) to find the first occurrence of the target value, which is the solution.
Solution Code
cpp
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
#include <cctype>
#include <cassert>
using namespace std;
const int MOD = 32768;
struct ArithmeticNode {
enum Type { Const, Variable, BinaryOp, FunctionCall };
Type type;
union {
int const_val;
struct {
char op;
ArithmeticNode* left;
ArithmeticNode* right;
};
struct FunctionChild {
ArithmeticNode* child;
};
};
~ArithmeticNode() {
if (type == BinaryOp) {
delete left;
delete right;
} else if (type == FunctionCall) {
delete child;
}
}
};
ArithmeticNode* ParseArithmetic(string& s, int& pos);
ArithmeticNode* ParseArithmetic(string& s, int& pos) {
// Begin parsing
auto ParseNumber = [&](int& p) -> ArithmeticNode* {
int val = 0, st = p;
while (p < s.size() && isdigit(s[p])) p++;
val = stoi(s.substr(st, p - st));
return new ArithmeticNode{ Constit const_val = val };
};
auto ParseVariable = [&] {
return new ArithmeticNode{ Vari };
};
auto ParseFunction = [&](int& p) -> ArithmeticNode* {
p += 2; // consume 'f('
ArithmeticNode* expr = ParseArithmetic(s, p);
// Now find closing )
int depth = 1;
while (p < s.size()) {
if (s[p] == '(') depth++;
else if (s[p] == ')') {
depth--;
if (depth == 0) {
p++; // move past the closing )
break;
}
}
p++;
}
return new ArithmeticNode{ FunctionCall, { .child = expr } };
};
auto ParseMultipler = [&]() -> ArithmeticNode* {
if (s[pos] == 'n') {
pos++;
return ParseVariable();
} else if (isdigit(s[pos])) {
return ParseNumber(pos);
} else if (s[pos] == 'f') {
return ParseFunction(pos); // read 'f(', parse inside, then closing )
} else if (s[pos] == '(') {
// Parse an expression in parentheses
pos++;
ArithmeticNode* val = ParseArithmetic(s, pos);
assert(s[pos] == ')');
pos++;
return val;
} else {
throw runtime_error("Parse error in multiplier");
}
};
auto ParseProduct = [&](int& pos) -> ArithmeticNode* {
ArithmeticNode* left = ParseMultipler();
while (pos < s.size() && (s[pos] == '*' || s[pos] == '/')) {
char op = s[pos++];
ArithmeticNode* right = ParseMultipler();
left = new ArithmeticNode{
BinaryOp,
{ op, left, right }
};
}
return left;
};
auto ParseSum = [&](int& pos) -> ArithmeticNode* {
ArithmeticNode* left = ParseProduct(pos);
while (pos < s.size() && (s[pos] == '+' || s[pos] == '-')) {
char op = s[pos++];
ArithmeticNode* right = ParseProduct(pos);
left = new ArithmeticNode{
BinaryOp,
{ op, left, right }
};
}
return left;
};
ArithmeticNode* ans = ParseSum(pos);
return ans;
};
struct LogicalNode {
ArithmeticNode* left;
ArithmeticNode* right;
char op;
~LogicalNode() {
delete left;
delete right;
}
};
LogicalNode* ParseLogical(string& s) {
// example: "n==0", "n<5"
int pos = 0;
auto ParseExpr = [&](int& p) -> ArithmeticNode* {
return ParseArithmetic(s, p);
};
// Find operator
int eqStart = s.find("==");
bool hasEq = eqStart != string::npos && (eqStart == 0 || !isdigit(s[eqStart-1]));
char op;
if (hasEq) {
op = '=';
// Split into left and right parts
string leftStr = s.substr(0, eqStart);
string rightStr = s.substr(eqStart+2);
int leftPos = 0, rightPos = 0;
ArithmeticNode* left = ParseExpr(leftPos);
ArithmeticNode* right = ParseExpr(rightPos);
return new LogicalNode{ left, right, '=' };
} else {
int gti = s.find('>');
int lti = s.find('<');
if (gti == string::npos && lti == string::npos) {
throw runtime_error("ParseLogical: No operator");
}
if (gti != string::npos && lti != string::npos) {
if (gti < lti) op = '>';
else op = '<';
} else {
op = (gti != string::npos) ? '>' : '<';
}
int opPos = (op == '>') ? gti : lti;
string leftStr = s.substr(0, opPos);
string rightStr = s.substr(opPos+1);
int leftPos = 0, rightPos =0;
ArithmeticNode* left = ParseExpr(leftPos);
ArithmeticNode* right = ParseExpr(rightPos);
return new LogicalNode{ left, right, op };
}
}
struct Operator {
enum Type { ReturnOp, IfOp };
Type type;
union {
ArithmeticNode* value;
struct {
LogicalNode* cond;
ArithmeticNode* val;
} ifop;
};
};
vector<Operator> parseOperators(string code) {
vector<Operator> ops;
vector<string> split;
{
// split code by ';'
stringstream ss(code);
string token;
while (getline(ss, token, ';')) {
if (token.empty()) continue;
split.push_back(token);
}
}
for (auto& t : split) {
string s = t;
string::iterator it = remove_if(s.begin(), s.end(), [](char c) -> bool {
return isspace(c);
});
s.resize(std::distance(s.begin(), it));
if (s.empty()) continue;
Operator op;
if (s.substr(0,6) == "return") {
op.type = Operator::ReturnOp;
op.value = ParseArithmetic(s.substr(6), 0);
} else if (s.substr(0,2) == "if") {
// if(LOGICAL)return expr
op.type = Operator::IfOp;
// First parse logical expression inside if ( ... )
int pos = 2;
assert(s[pos] == '(');
// extract the logical expr part
string logExprStr = "";
int depth =1;
int i =3; // past '('
while (i < s.size() && depth !=0) {
if (s[i] == '(') depth++;
else if (s[i] == ')') depth--;
logExprStr += s[i];
i++;
}
logExprStr.erase(logExprStr.find_last_not_of(")")+1); // remove the closing
LogicalNode* lNode = ParseLogical( logExprStr.substr(0, logExprStr.size()-1) ); // removing the last ) ?
op.ifop.cond = lNode;
// now the return expr is the rest of the token after ")return.."
string retPart = s.substr(i, s.size());
if (retPart.find("return") !=0) {
cout << "Error parsing ret expr" << endl;
assert(1 ==0);
}
retPart = retPart.substr(6); // drop 'return'
op.ifop.val = ParseArithmetic(retPart, 0);
}
else {
throw runtime_error("Unknown operator type in parsing");
}
ops.push_back(op);
}
return ops;
}
int evaluate(ArithmeticNode* node, int n, const vector<int>& F) {
if (node->type == ArithmeticNode::Const) {
return node->const_val % MOD;
} else if (node->type == ArithmeticNode::Variable) {
return n % MOD;
} else if (node->type == ArithmeticNode::BinaryOp) {
int a = evaluate(node->left , n, F);
int b = evaluate(node->right, n, F);
if (node->op == '+') return (a + b) % MOD;
else if (node->op == '-') {
int diff = (a - b) % MOD;
if (diff < 0) diff += MOD;
return diff;
}
else if (node->op == '*') return (a * b) % MOD;
else if (node->op == '/') {
if (b == 0) throw runtime_error("Division by zero");
return a / b;
}
else throw runtime_error("Unknown binary operator");
} else if (node->type == ArithmeticNode::FunctionCall) {
int k = evaluate(node->FunctionChild.child, n, F);
return F[ k % MOD ]; // ensure within bounds
}
return -1;
}
bool evaluateLogical(LogicalNode* node, int n, const vector<int>& F) {
int left_val = evaluate(node->left, n, F) % MOD;
int right_val = evaluate(node->right, n, F) % MOD;
switch (node->op) {
case '=':
return left_val == right_val;
case '>':
return left_val > right_val;
case '<':
return left_val < right_val;
default:
return false;
}
}
int main() {
int target;
cin >> target;
cin.ignore();
// Read all lines for the function code
string code;
while (getline(cin, std::string line)) {
code += line;
}
// Preprocess the code
code.erase(remove_if(code.begin(), code.end(), isspace), code.end());