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 that results in the given function f(n) returning a specific target value. The function is provided in a simplified C++ syntax, and we must account for the 15-bit Berland compiler's arithmetic operations. Our task is to find the maximum n for which the function returns the target value, or output -1 if no such n exists.
Approach
Parse the Function Code: Extract and parse the function's operators (return and conditional return statements) from the given input.
Precompute Values: Evaluate the function f(n) for all values of n from 0 to 32767 using dynamic programming to store previously computed values (memoization). This avoids redundant calculations and leverages the small input range constraint.
Evaluate for Target: Search for the largest n such that f(n) equals the given target value.
Solution Code
cpp
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <cctype>
#include <functional>
using namespace std;
struct ExprNode;
using EvalFunc = function<int(int, const vector<int>&)>;
vector<string> tokens;
int token_pos = 0;
enum TokenType {
IF_, RETURN_, VAR_N, FUNCTION_F, LNGT, LNLT, LEQ,
PLUS, MINUS, MUL, DIV, LPAREN, RPAREN, SEMI, NUMBER
};
const map<string, TokenType> keyword_map = {
{"if", IF_},
{"return", RETURN_}
};
const map<string, TokenType> op_map = {
{">", LNGT},
{"<", LNLT},
{"==", LEQ},
{"+", PLUS},
{"-", MINUS},
{"*", MUL},
{"/", DIV},
{"(", LPAREN},
{")", RPAREN},
{";", SEMI}
};
class ExprNode {
public:
virtual int evaluate(int n, const vector<int>& memo) = 0;
};
class LiteralExpr : public ExprNode {
int value;
public:
LiteralExpr(int v) : value(v) {}
int evaluate(int, const vector<int>&) override {
return value;
}
};
class VarNExpr : public ExprNode {
public:
VarNExpr() {}
int evaluate(int n, const vector<int>&) override {
return n;
}
};
class FuncCallExpr : public ExprNode {
ExprNode* arg;
public:
FuncCallExpr(ExprNode* a) : arg(a) {}
int evaluate(int n, const vector<int>& memo) override {
int arg_val = arg->evaluate(n, memo);
return memo[arg_val];
}
};
class BinOpExpr : public ExprNode {
char op;
ExprNode* left;
ExprNode* right;
int apply(int a, int b) const {
switch (op) {
case '+':
return (a + b) % 32768;
case '-':
return (a - b) % 32768;
case '*':
return (a * b) % 32768;
case '/':
return a / b;
default:
return 0;
}
}
public:
BinOpExpr(char o, ExprNode* l, ExprNode* r) : op(o), left(l), right(r) {}
int evaluate(int n, const vector<int>& memo) override {
return apply(left->evaluate(n, memo), right->evaluate(n, memo));
}
};
ExprNode* parseParen(ExprNode* expr) {
return expr;
}
ExprNode* parseArithmExpr();
ExprNode* parseProduct() {
auto left = parseMultiplier();
while (token_pos < tokens.size()) {
auto& token = tokens[token_pos];
if (token == "*") {
token_pos++;
auto right = parseMultiplier();
left = new BinOpExpr('*', left, right);
} else if (token == "/") {
token_pos++;
auto right = parseMultiplier();
left = new BinOpExpr('/', left, right);
} else {
break;
}
}
return left;
}
ExprNode* parseSum() {
auto left = parseProduct();
while (token_pos < tokens.size()) {
auto& token = tokens[token_pos];
if (token == "+" || token == "-") {
char op = tokens[token_pos][0];
token_pos++;
auto right = parseProduct();
left = new BinOpExpr(op, left, right);
} else {
break;
}
}
return left;
}
ExprNode* parseMultiplier() {
if (token_pos >= tokens.size())
return nullptr;
string token = tokens[token_pos];
if (token == "n") {
token_pos++;
return new VarNExpr();
} else if (isdigit(token[0])) {
int value = stoi(token);
token_pos++;
return new LiteralExpr(value);
} else if (token == "f") {
token_pos++;
if (tokens[token_pos] != "(") {
// error
return nullptr;
}
token_pos++;
auto arg = parseArithmExpr();
if (tokens[token_pos] != ")") {
// error
return nullptr;
}
token_pos++;
return new FuncCallExpr(arg);
}
return nullptr;
}
ExprNode* parseArithmExpr() {
return parseSum();
}
ExprNode* parseLogicalExpr(TokenType& op_out, ExprNode*& right_out, vector<string>& tokens, int& pos) {
Throw for easy parsing, assuming tokens and calling conveniences.
auto left = parseArithmExpr();
string op;
if (tokens[token_pos] == ">" || tokens[token_pos] == "<" || tokens[token_pos] == "==") {
op = tokens[token_pos];
token_pos++;
}
right_out = parseArithmExpr();
// These are temporary placeholders, would set op_out based on op.
op_out = (op == ">" ? LNGT : (op == "<" ? LNLT : (op == "==" ? LEQ : 0)));
return left;
}
// 略过一些函数和 referring to parsed functions,这里简化.
class Operator {
public:
enum Type { RETURN_, IF_RETURN_ };
Type type;
// For RETURN:
ExprNode* ret_expr;
// For IF_RETURN:
TokenType cond_op;
ExprNode* left_cond;
ExprNode* right_cond;
ExprNode* ret_cond_expr;
Operator(Type t, ExprNode* e) : type(t), ret_expr(e) {}
Operator(TokenType op, ExprNode* l, ExprNode* r, ExprNode* e)
: type(IF_RETURN_), cond_op(op), left_cond(l), right_cond(r), ret_cond_expr(e) {}
int evaluate(int n, const vector<int>& memo) const {
if (type == RETURN_) {
return ret_expr->evaluate(n, memo);
} else {
int lval = left_cond->evaluate(n, memo);
int rval = right_cond->evaluate(n, memo);
bool cond = false;
switch (cond_op) {
case LNGT:
cond = (lval > rval);
break;
case LNLT:
cond = (lval < rval);
break;
case LEQ:
cond = (lval == rval);
break;
}
if (cond) {
return ret_cond_expr->evaluate(n, memo);
}
}
return -1; // Not satisfying the condition
}
};
vector<Operator> parseOperators(const vector<string>& tokens) {
vector<Operator> ops;
token_pos = 0;
while (token_pos < tokens.size()) {
string tok = tokens[token_pos];
if (tok == "return") {
token_pos++; // Move past "return"
auto expr = parseArithmExpr();
// Skip the semicolon.
token_pos++;
ops.push_back(Operator(Operator::RETURN_, expr));
} else if (tok == "if") {
token_pos++; // Move past "if"
// Parse condition inside if
token_pos++; // past '('
TokenType op;
ExprNode* right_cond;
auto left_cond = parseArithmExpr();
op = ...;
right_cond = ...; // need correct parsing from parseLogicalExpr
// Then the operator )
token_pos++; // ')'
// Expect "RETURN ... ;"
string return_tok = tokens[token_pos];
token_pos++;
auto ret_expr = ...// parseArithmExpr...
// skip semicolon.
token_pos++;
ops.push_back(Operator(op, left_cond, right_cond, ret_expr));
}
}
return ops;
}
int main() {
int target;
cin >> target;
string code;
// Read the function code until end.
string rest;
for (string line; getline(cin, line);) {
rest += line;
}
// Process the function code.
// Tokenize the function body (code) excluding the first line function declaration.
tokens.clear();
string code_body;
size_t pos = rest.find("{");
int start = rest.find("{");
if (start != string::npos) {
code_body = rest.substr(start + 1);
size_t end = code_body.find("}");
code_body = code_body.substr(0, end);
}
// 清洗 code_body of whitespace and form tokens.
string current = "";
for (char c : code_body) {
if (isspace(c)) continue;
if (ispunct(c) || c == '<' || c == '>' || c == '=') {
if (!current.empty()) {
tokens.push_back(current);
current = "";
}
if (c == '=' && current == "==") continue; // handles "=="
current += c;
} else if (isdigit(c)) {
current += c;
} else {
if (!current.empty()) tokens.push_back(current);
current = c;
if (!current.empty()) tokens.push_back(current);
current = "";
}
}
if (!current.empty()) {
tokens.push_back(current);
}
// Parse the operators from