Skip to content

Instantly share code, notes, and snippets.

@kunishi
Created October 8, 2015 02:31
Show Gist options
  • Save kunishi/591f5de9896f9128a9ca to your computer and use it in GitHub Desktop.
Save kunishi/591f5de9896f9128a9ca to your computer and use it in GitHub Desktop.
/* @JUDGE_ID: 26089BN 112 C "" */
#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
#define NULLNODE 2
char c;
char next;
char skip_ws()
{
c = next;
do {
next = getc(stdin);
} while (next == ' ' || next == '\t' || next == '\n');
return c;
}
int traverse(int sum, int target)
{
int n = 0;
int isleaf = TRUE;
int left, right;
int finished_left = FALSE;
int negative = FALSE;
#if 0
printf("call traverse: %d, %d\n", sum, target);
#endif
while (1) {
switch ((c = skip_ws())) {
case '-':
negative = TRUE;
break;
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '0':
isleaf = FALSE;
n = n * 10 + (c - '0');
break;
case '(':
if (finished_left == FALSE) {
if (negative == TRUE) {
n = -n;
}
#if 0
printf("traverse left: %d, %d, %d\n", sum, n, target);
#endif
left = traverse(sum + n, target);
#if 0
printf("traverse left finished: %d\n", left);
#endif
finished_left = TRUE;
} else {
#if 0
printf("traverse right: %d, %d, %d\n", sum, n, target);
#endif
right = traverse(sum + n, target);
#if 0
printf("traverse right finished: %d\n", right);
#endif
}
break;
case ')':
if (isleaf == TRUE) {
return NULLNODE;
}
if (left == NULLNODE && right == NULLNODE) {
#if 0
printf("judgment: %d, %d, %d\n", sum, n, target);
#endif
if (sum + n == target) {
return TRUE;
} else {
return FALSE;
}
} else if (left == TRUE || right == TRUE) {
return TRUE;
} else {
return FALSE;
}
case EOF:
return;
}
}
}
int main() {
int target = 0;
int result;
int negative = FALSE;
next = getc(stdin); /* initialize */
while ((c = skip_ws(stdin)) != EOF) {
if (c == '-') {
negative = TRUE;
}
if (c >= '0' && c <= '9') {
target = 10 * target + (c - '0');
}
if (c == '(') {
if (negative == TRUE) {
target = -target;
}
result = traverse(0, target);
#if 0
printf("traverse: 0, %d, %d\n", target, result);
#endif
if (result == TRUE) {
printf("yes\n");
} else {
printf("no\n");
}
target = 0;
negative = FALSE;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment