QOJ.ac
QOJ
ID | 题目 | 提交者 | 结果 | 用时 | 内存 | 语言 | 文件大小 | 提交时间 | 测评时间 |
---|---|---|---|---|---|---|---|---|---|
#694382 | #5307. Subgraph Isomorphism | Calculatelove# | RE | 0ms | 0kb | C++14 | 3.2kb | 2024-10-31 17:49:57 | 2024-10-31 17:50:02 |
answer
#include <bits/stdc++.h>
typedef unsigned long long u64;
const int N = 100100;
int n, m;
int tot, head[N], ver[N * 2], Next[N * 2];
void add_edge(int u, int v) {
ver[++ tot] = v; Next[tot] = head[u]; head[u] = tot;
}
int dep[N];
int top, stk[N];
int seqlen, seq[N];
bool exist[N];
bool ok;
void dfs(int u, int fu) {
if (ok) return;
dep[u] = dep[fu] + 1;
stk[++ top] = u;
for (int i = head[u]; i; i = Next[i]) {
int v = ver[i];
if (v == fu) continue;
if (!dep[v]) {
dfs(v, u);
} else if (dep[v] < dep[u]) {
int x;
do {
x = stk[top --];
seq[++ seqlen] = x;
} while (x != v);
ok = 1;
return;
}
}
top --;
}
u64 f[N];
u64 mask = std::mt19937_64((unsigned)time(0))();
u64 shift(u64 x) {
x ^= mask;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x ^= mask;
return x;
}
void dfs_hash(int u, int fu) {
f[u] = 1;
for (int i = head[u]; i; i = Next[i]) {
int v = ver[i];
if (v == fu || exist[v]) continue;
dfs_hash(v, u);
f[u] += shift(f[v]);
}
}
const u64 P = 13331;
u64 power[N];
u64 pre[N], pre_suf[N];
u64 suf[N], suf_pre[N];
void work() {
scanf("%d%d", &n, &m);
if (n == m) {
tot = 0;
for (int i = 1; i <= n; i ++) head[i] = 0;
for (int i = 1, u, v; i <= m; i ++) {
scanf("%d%d", &u, &v);
add_edge(u, v), add_edge(v, u);
}
} else {
for (int i = 1, u, v; i <= m; i ++)
scanf("%d%d", &u, &v);
if (m == n - 1)
puts("YES");
else
puts("NO");
return;
}
for (int i = 1; i <= n; i ++) dep[i] = 0;
for (int i = 1; i <= n; i ++) exist[i] = 0;
top = 0, seqlen = 0;
ok = 0, dfs(1, 0);
for (int i = 1; i <= seqlen; i ++) exist[seq[i]] = 1;
for (int i = 1; i <= seqlen; i ++) dfs_hash(i, 0);
power[0] = 1;
for (int i = 1; i <= seqlen; i ++) power[i] = power[i - 1] * P;
pre[0] = 0;
for (int i = 1; i <= seqlen; i ++) pre[i] = pre[i - 1] * P + f[seq[i]];
pre_suf[0] = 0;
for (int i = 1; i <= seqlen; i ++) pre_suf[i] = pre_suf[i - 1] + power[i - 1] * f[seq[i]];
suf[seqlen + 1] = 0;
for (int i = seqlen; i >= 1; i --) suf[i] = suf[i + 1] * P + f[seq[i]];
suf_pre[seqlen + 1] = 0;
for (int i = seqlen; i >= 1; i --) suf_pre[i] = suf_pre[i + 1] + power[seqlen - i] * f[seq[i]];
for (int i = 1; i <= seqlen; i ++)
assert(pre[i] == suf[seqlen - i + 1]);
for (int i = 1; i < seqlen; i ++) {
u64 hash_pre = power[i] * suf_pre[i + 1] + pre[i];
u64 hash_suf = power[seqlen - i] * pre_suf[i] + suf[i + 1];
if (hash_pre == pre[seqlen] || hash_suf == pre[seqlen] || hash_pre == suf[1] || hash_suf == suf[1]);
else {
puts("NO");
return;
}
}
puts("YES");
}
int main() {
int T;
scanf("%d", &T);
while (T --)
work();
return 0;
}
详细
Test #1:
score: 0
Runtime Error
input:
4 7 6 1 2 2 3 3 4 4 5 5 6 3 7 3 3 1 2 2 3 3 1 5 5 1 2 2 3 3 4 4 1 1 5 1 0