Submission #407376

# Submission time Handle Problem Language Result Execution time Memory
407376 2021-05-18T20:21:21 Z rainboy Slon (COCI15_slon) C
120 / 120
5 ms 460 KB
#include <ctype.h>
#include <stdio.h>
#include <string.h>

#define N	100000

int md;

int parse_expr(char *cc, int n, int *a_, int *b_);

int parse_factor(char *cc, int n, int *a_, int *b_) {
	int i;

	if (cc[0] == 'x') {
		*a_ = 1, *b_ = 0;
		return 1;
	} else if (isdigit(cc[0])) {
		i = 0, *a_ = *b_ = 0;
		while (i < n && isdigit(cc[i]))
			*b_ = (*b_ * 10 + (cc[i++] - '0')) % md;
		return i;
	} else {
		i = 1 + parse_expr(cc + 1, n - 1, a_, b_);
		return i + 1;
	}
}

int parse_term(char *cc, int n, int *a_, int *b_) {
	int i, j, a, b;

	*a_ = 0, *b_ = 1, i = 0;
	while (1) {
		j = i + parse_factor(cc + i, n - i, &a, &b);
		*a_ = ((long long) *a_ * b + (long long) *b_ * a) % md, *b_ = (long long) *b_ * b % md;
		if (j == n || cc[j] != '*')
			return j;
		i = j + 1;
	}
}

int parse_expr(char *cc, int n, int *a_, int *b_) {
	int i, j, a, b;

	*a_ = 0, *b_ = 0, i = 0;
	while (1) {
		j = i + parse_term(cc + i, n - i, &a, &b);
		if (i == 0 || cc[i - 1] == '+')
			*a_ = (*a_ + a) % md, *b_ = (*b_ + b) % md;
		else
			*a_ = (*a_ - a + md) % md, *b_ = (*b_ - b + md) % md;
		if (j == n || cc[j] != '+' && cc[j] != '-')
			return j;
		i = j + 1;
	}
}

int main() {
	static char cc[N + 1];
	int n, a, b, c, x;

	scanf("%s%d%d", cc, &c, &md), n = strlen(cc);
	parse_expr(cc, n, &a, &b);
	for (x = 0; x < md; x++)
		if (((long long) a * x + b) % md == c) {
			printf("%d\n", x);
			return 0;
		}
	return 0;
}

Compilation message

slon.c: In function 'parse_expr':
slon.c:51:30: warning: suggest parentheses around '&&' within '||' [-Wparentheses]
   51 |   if (j == n || cc[j] != '+' && cc[j] != '-')
      |                 ~~~~~~~~~~~~~^~~~~~~~~~~~~~~
slon.c: In function 'main':
slon.c:61:2: warning: ignoring return value of 'scanf' declared with attribute 'warn_unused_result' [-Wunused-result]
   61 |  scanf("%s%d%d", cc, &c, &md), n = strlen(cc);
      |  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Verdict Execution time Memory Grader output
1 Correct 5 ms 256 KB Output is correct
2 Correct 3 ms 460 KB Output is correct
3 Correct 1 ms 204 KB Output is correct
4 Correct 2 ms 204 KB Output is correct
5 Correct 1 ms 204 KB Output is correct
6 Correct 3 ms 204 KB Output is correct
7 Correct 1 ms 204 KB Output is correct
8 Correct 1 ms 332 KB Output is correct
9 Correct 2 ms 292 KB Output is correct
10 Correct 2 ms 332 KB Output is correct