偏序关系用分治优化建图:ARC165F

本文搬运自本人高中时期CSDN博客,若图片加载不出来,可到原文查看:https://blog.csdn.net/zhangtingxiqwq/article/details/134253598

https://atcoder.jp/contests/arc165/tasks/arc165_f

首先可以建图,然后变成求字典序最小的的拓扑排序

然后发现这样复杂度会炸,观察连边的条件是什么:

  • li<ljl_i<l_j

  • ri<rjr_i<r_j

这是个二维偏序问题,我们考虑用分治来解决

我们按 ll 排序,本区间内再按 rr 排序:

在这里插入图片描述

复杂度 O(nlog2n)O(n\log^2n)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include<bits/stdc++.h>
using namespace std;
#ifdef LOCAL
#define debug(...) fprintf(stdout, ##__VA_ARGS__)
#else
#define debug(...) void(0)
#endif
//#define int long long
inline int read(){int x=0,f=1;char ch=getchar(); while(ch<'0'||
ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9'){
x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}return x*f;}
#define Z(x) (x)*(x)
#define pb push_back
#define fi first
#define se second
//srand(time(0));
#define N 5000010
//#define M
//#define mo
struct node {
int l, r, id, op;
}a[N];
int n, m, i, j, k, T;
struct cmp {
bool operator () (int x, int y) const {
if(x<=n && y>n) return 1;
if(y<=n && x>n) return 0;
if(x<=n && y<=n) return x>y;
if(x>n && y>n) return x>y;
}
};
priority_queue<int, vector<int>, cmp >q;
int c[N], b[N], tot;
vector<int>G[N];

void cun(int x, int y) {
// debug("%d -> %d\n", x, y);
G[x].pb(y); ++c[y];
}

void solve(int l, int r) {
int i;
if(l==r) return ;
int mid=(l+r)>>1;
solve(l, mid); solve(mid+1, r);
for(i=l; i<=mid; ++i) a[i].op=0;
for(i=mid+1; i<=r; ++i) a[i].op=1;
sort(a+l, a+r+1, [&] (node x, node y) { return x.r<y.r; });
for(i=l; i<=r; ++i) b[i]=++tot;
for(i=l; i<=r-1; ++i) cun(b[i], b[i]+1);
for(i=l; i<=r; ++i)
if(a[i].op==0) cun(a[i].id, b[i]);
else cun(b[i], a[i].id);
}

signed main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
#endif
// T=read();
// while(T--) {
//
// }
n=read(); tot=n;
for(i=1; i<=n; ++i) a[i].id=i;
for(i=1; i<=2*n; ++i) {
k=read();
if(!a[k].l) a[k].l=i; else a[k].r=i;
}
sort(a+1, a+n+1, [] (node x, node y) { return x.l<y.l; });
solve(1, n);
for(i=1; i<=tot; ++i) if(!c[i]) q.push(i);
while(!q.empty()) {
auto u=q.top(); q.pop();
// debug("# %d\n", u);
if(u<=n) printf("%d %d ", u, u);
for(auto v : G[u])
if(--c[v]==0) q.push(v);
}
return 0;
}