Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- enum{ MAXN = (int)2e6 };
- typedef struct list
- {
- char type;
- long long key;
- struct list *next;
- } list;
- char s[MAXN];
- list* brackets[MAXN];
- long long getnum(int it)
- {
- while ((s[it] != '\0') && (s[it] == '0'))
- ++it;
- if (s[it] < '0' || '9' < s[it])
- return 0;
- int curr = it;
- while ((s[curr] != '\0') && (('0' <= s[curr]) && (s[curr] <= '9')))
- ++curr;
- --curr;
- long long res = 0;
- int p = 0;
- while (it <= curr)
- {
- if (!p)
- p = 1;
- res += (s[curr] - '0') * p;
- --curr;
- p *= 10;
- }
- return res;
- }
- long long compute(list *tmp)
- {
- int sum = 0;
- int current = 0;
- int sign = 1;
- tmp = tmp->next;
- if (tmp->type == '-')
- sign = -1, tmp = tmp->next;
- while (tmp->type != ')')
- {
- current = tmp->key;
- tmp = tmp->next;
- char operation = tmp->type;
- while ((operation == '*' || operation == '/') && (tmp->next->type != ')'))
- {
- if (operation == '*')
- current *= tmp->next->key;
- else
- current /= tmp->next->key;
- tmp = tmp->next->next;
- operation = tmp->type;
- }
- current *= sign;
- sum += current;
- char oper = tmp->type;
- if (oper == '-' || oper == '+')
- {
- tmp = tmp->next;
- if (oper == '-')
- sign = -1;
- else
- sign = 1;
- }
- }
- return sum;
- }
- int main(void)
- {
- FILE* in = fopen("input.txt", "r");
- FILE* out = fopen("output.txt", "w");
- fgets(s, MAXN, in);
- int it = 0;
- list *buff = malloc(sizeof(list));
- buff->type = '(';
- list *stak = buff;
- while (s[it] != '\0')
- {
- if (('0' <= s[it]) && (s[it] <= '9'))
- {
- int curr = getnum(it);
- buff->next = malloc(sizeof(list));
- buff = buff->next;
- buff->type = 'i';
- buff->key = curr;
- while ((s[it] != '\0') && (('0' <= s[it]) && (s[it] <= '9')))
- ++it;
- --it;
- }
- else if (s[it] != ' ')
- {
- buff->next = malloc(sizeof(list));
- buff = buff->next;
- buff->type = s[it];
- }
- ++it;
- }
- buff->next = malloc(sizeof(list));
- buff = buff->next;
- buff->type = ')';
- buff->next = NULL;
- int currbr = 0;
- while (stak)
- {
- if (stak->type == '(')
- {
- brackets[currbr] = stak;
- ++currbr;
- }
- if (stak->type == ')')
- {
- --currbr;
- long long res = compute(brackets[currbr]);
- brackets[currbr]->type = 'i';
- brackets[currbr]->key = res;
- brackets[currbr]->next = stak->next;
- }
- stak = stak->next;
- }
- fprintf(out, "%d", brackets[currbr]->key);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment