結果
問題 | No.1778 括弧列クエリ / Bracketed Sequence Query |
ユーザー |
👑 |
提出日時 | 2021-12-07 00:50:19 |
言語 | C (gcc 13.3.0) |
結果 |
RE
|
実行時間 | - |
コード長 | 1,682 bytes |
コンパイル時間 | 251 ms |
コンパイル使用メモリ | 31,732 KB |
実行使用メモリ | 38,676 KB |
最終ジャッジ日時 | 2024-07-07 10:01:45 |
合計ジャッジ時間 | 8,360 ms |
ジャッジサーバーID (参考情報) |
judge2 / judge1 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 24 RE * 1 TLE * 1 -- * 1 |
ソースコード
#include <stdio.h>typedef struct Edge {struct Edge *next;int v;} edge;int main(){int i, N, Q;char S[200001];scanf("%d %d", &N, &Q);scanf("%s", S);int u, w, M = 0, stack[200001], head = 0, indeg[200001] = {}, mate[200001], flag[200001];edge *adj[200001] = {}, e[200001], *p;for (i = 0; i < N; i++) {if (S[i] == '(') stack[head++] = i + 1;else {head--;mate[i+1] = stack[head];mate[stack[head]] = i + 1;flag[i+1] = -1;flag[stack[head]] = 1;if (head == 0) continue;u = stack[head-1];w = stack[head];e[M].v = w;e[M].next = adj[u];adj[u] = &(e[M++]);indeg[w]++;}}int j, x, depth[200001], par[200001][20], q[200001], tail;for (i = 1, depth[0] = -1; i <= N; i++) {if (indeg[i] != 0 || flag[i] < 0) continue;q[0] = i;depth[i] = 0;par[i][0] = 0;for (head = 0, tail = 1; head < tail; head++) {u = q[head];for (p = adj[u]; p != NULL; p = p->next) {w = p->v;depth[w] = depth[u] + 1;par[w][0] = u;for (j = 1, x = par[u][0]; x != 0; par[w][j] = x, x = par[x][j-1], j++);par[w][j] = 0;q[tail++] = w;}}}for (i = 1; i <= Q; i++) {scanf("%d %d", &u, &w);if (flag[u] < 0) u = mate[u];if (flag[w] < 0) w = mate[w];while (depth[u] > depth[w]) {for (j = 0; depth[par[u][j+1]] >= depth[w]; j++);u = par[u][j];}while (depth[w] > depth[u]) {for (j = 0; depth[par[w][j+1]] >= depth[u]; j++);w = par[w][j];}while (u != w) {for (j = 0; par[u][j+1] != par[w][j+1]; j++);u = par[u][j];w = par[w][j];}if (u != 0) printf("%d %d\n", u, mate[u]);else printf("-1\n");}fflush(stdout);return 0;}