Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- struct node_s {
- int idx, pos, anc, pes;
- };
- void preprocess (struct node_s ***T, char *S, int *P, int N) {
- int i, j, k;
- struct node_s **t = (*T);
- i = 0;
- j = 0;
- while (i < 2*N) {
- if (S[i] == '(') {
- struct node_s *n = t[j];
- n->idx = j;
- n->pos = i;
- n->pes = P[j];
- j++;
- }
- i++;
- }
- t[0]->anc = -1;
- for (i = 1; i < N; ++i) {
- int count = -1;
- for (j = t[i]->pos; (j > 0) && (count != 0); --j)
- count += (S[j-1] == '(') ? 1 : -1;
- for (k = 0; k < N; ++k)
- if (t[k]->pos == j) {
- t[i]->anc = k;
- break;
- }
- }
- }
- int find_node (struct node_s ***T, int v, int P) {
- struct node_s **t = (*T);
- struct node_s *cur = t[v];
- struct node_s *anc = t[cur->anc];
- while ((anc->anc != -1) && (anc->pes >= P)) {
- cur = t[cur->anc];
- anc = t[cur->anc];
- }
- if ((anc->anc == -1) && (anc->pes >= P))
- return anc->idx;
- return cur->idx;
- }
- int main(int argc, char *argv) {
- int i, N;
- char *S, *W;
- int *P;
- int Q;
- char **queries;
- char *line = NULL;
- size_t size;
- int line_number = 1;
- char *seps = " ";
- char *token;
- while (getline(&line, &size, stdin) > 0) {
- line[strcspn(line, "\n")] = 0;
- switch (line_number) {
- case 1:
- N = atoi(line);
- break;
- case 2:
- S = malloc(sizeof(char) * N);
- strcpy(S, line);
- break;
- case 3:
- i = 0;
- token = strtok(line, seps);
- P = malloc(sizeof(int) * N);
- while (token != NULL && i < N) {
- int var;
- sscanf(token, "%d", &var);
- P[i++] = var;
- token = strtok(NULL, seps);
- }
- break;
- case 4:
- Q = atoi(line);
- queries = malloc(sizeof(char *) * Q);
- break;
- default:
- queries[line_number-5] = malloc(sizeof(char) * 3);
- strcpy(queries[line_number-5], line);
- break;
- }
- line_number++;
- }
- struct node_s **t = malloc(sizeof(struct node_s*) * N);
- for (i = 0; i < N; ++i)
- t[i] = malloc(sizeof(struct node_s));
- preprocess(&t, S, P, N);
- printf("%d\n", Q);
- for (i = 0; i < Q; i++) {
- int j = 0;
- int params[2];
- token = strtok(queries[i], seps);
- while (token != NULL && j < 2) {
- int var;
- sscanf(token, "%d", &var);
- params[j++] = var;
- token = strtok(NULL, seps);
- }
- int result = find_node(&t, params[0], params[1]);
- printf("%d\n", result);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement