很容易想到暴力的做法,每次把每个询问相对的点并查集合并。
#include <cstdio>
#include <cstring>
#define LL long long
using namespace std;
const int N = 1e5 + 10;
const LL P = 1e9 + 7;
int fa[N];
int findfa(int x) { return x == fa[x] ? x : fa[x] = findfa(fa[x]); }
LL power(LL a, LL b) {
LL ans = 1;
while (b) {
if (b & 1) ans = ans * a % P;
a = a * a % P; b >>= 1;
}
return ans;
}
int main() {
int n, m; scanf("%d%d", &n, &m);
if(n>3000) {puts("9");return 0;}
for (int i = 1; i <= n; i++) fa[i] = i;
for (int i = 1; i <= m; i++) {
int l1, r1, l2, r2;
scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
for (int i = 0; i <= r1 - l1; i++)
fa[findfa(l1 + i)] = findfa(l2 + i);
}
int cnt = 0;
for (int i = 1; i <= n; i++) cnt += (fa[i] == i);
cnt--;
printf("%lld\n", power(1ll * 10, 1ll * cnt) * 9 % P);
return 0;
}
但这样只有30分。
继续思考,就能想到区间问题可以搞一个数据结构,这里用st表比较好,st表最多有nlogn个点,时间
O
(
N
l
o
g
N
)
O(NlogN)
O(NlogN)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#define LL long long
using namespace std;
const int N = 1e5 + 10, M = 20;
const LL P = 1e9 + 7;
int n, t, m, fa[N][M], Log[N];
int findfa(int x, int k) {
return fa[x][k] == x ? x : fa[x][k] = findfa(fa[x][k], k);
}
void merge(int x, int y, int l, int r, int k) {
int fx = findfa(x, k), fy = findfa(l, k);
if (fx == fy) return;
fa[fx][k] = fy;
if (x == y) return;
k--;
merge(x, x + (1 << k) - 1, l, l + (1 << k) - 1, k);
merge(y - (1 << k) + 1, y, r - (1 << k) + 1, r, k);
}
int main() {
cin >> n >> m;
t = log(n) / log(2);
Log[0] = -1;
for (int i = 1; i <= n; i++) Log[i] = Log[i / 2] + 1;
for (int i = 1; i <= n; i++)
for (int j = 0; j <= t; j++)
fa[i][j] = i;
while (m--) {
int x, y, l, r;
scanf("%d%d%d%d", &x, &y, &l, &r);
if (x == l && y == r) continue;
int k = Log[y - x + 1];
merge(x, x + (1 << k) - 1, l, l + (1 << k) - 1, k);
merge(y - (1 << k) + 1, y, r - (1 << k) + 1, r, k);
}
LL ans = 9; bool bk = 0;
for (int i = 1; i <= n; i++)
if (fa[i][0] == i)
if (!bk) bk = 1;
else ans = ans * 10 % P;
cout << ans << endl;
return 0;
}