题解:P13524 [KOI 2025 #2] 跳跃
wangyibo201026 · · 题解
一眼顶真,鉴定为神秘复杂度联考和原题都卡不掉。
首先发现从
然后先差分,相当于每次对
接下来我们考虑从前往后构造每个区间,用一个 multiset 存储后面有哪些位置的
这样匹配当枚举到
你如果构造一组比较大(
我们充分发扬人类智慧! 从前往后在 multiset 中枚举第一个/第一对构造成区间对后不会成环的右端点(用并查集维护),强行构造,我认为复杂度最坏会被卡到
正确做法好像并不复杂,这里只是分享我考场上的思路。
code:
#include <bits/stdc++.h>
// #define int long long
using namespace std;
const int N = 1e6 + 5;
int n, cnt;
int a[N], tmp[N], in[N], fa[N], siz[N];
vector < pair < int, int > > ans;
vector < int > e[N];
multiset < int > f, g; // f -> +1, g -> -1
int find ( int x ) {
if ( fa[x] == x ) {
return x;
}
return fa[x] = find ( fa[x] );
}
inline void unionn ( int x, int y ) {
x = find ( x ), y = find ( y );
if ( x != y ) {
if ( siz[x] > siz[y] ) {
swap ( x, y );
}
fa[x] = y;
siz[y] += siz[x];
}
}
void dfs ( int x, int fa ) {
cout << x << " ";
for ( int v : e[x] ) {
if ( v != fa ) {
dfs ( v, x );
}
}
}
signed main () {
freopen ( "paper.in", "r", stdin );
freopen ( "paper.out", "w", stdout );
ios :: sync_with_stdio ( false );
cin.tie ( 0 ), cout.tie ( 0 );
cin >> n;
for ( int i = 1; i < n; i ++ ) {
cin >> a[i];
}
for ( int i = n - 1; i >= 1; i -- ) {
a[i] -= a[i - 1];
tmp[i] = a[i];
}
g.insert ( n ); // n -> -1
for ( int i = 2; i < n; i ++ ) {
if ( a[i] == 2 ) {
f.insert ( i ), f.insert ( i );
}
else if ( a[i] == 0 ) {
f.insert ( i ), g.insert ( i );
}
else {
g.insert ( i ), g.insert ( i );
}
}
for ( int i = 1; i <= n; i ++ ) {
fa[i] = i;
siz[i] = 1;
}
for ( int i = 1; i < n; i ++ ) {
if ( i == 1 ) {
int x = *g.begin ();
g.erase ( g.find ( x ) );
ans.push_back ( { 1, x } );
a[x] ++, a[i] --;
unionn ( 1, x );
}
else {
if ( a[i] == 2 ) {
int x, y;
for ( int it : g ) {
if ( find ( it ) != find ( i ) ) {
x = it;
break;
}
}
for ( int it : g ) {
if ( find ( it ) != find ( i ) && it != x && find ( it ) != find ( x ) ) {
y = it;
break;
}
}
g.erase ( g.find ( x ) ), g.erase ( g.find ( y ) );
g.erase ( i );
a[x] ++, a[y] ++, a[i] --, a[i] --;
ans.push_back ( { i, x } ), ans.push_back ( { i, y } );
unionn ( i, x ), unionn ( i, y );
}
else if ( a[i] == 1 ) {
int x;
for ( int it : g ) {
if ( find ( it ) != find ( i ) ) {
x = it;
break;
}
}
g.erase ( g.find ( x ) );
g.erase ( i );
a[x] ++, a[i] --;
ans.push_back ( { i, x } );
unionn ( i, x );
}
}
}
for ( pair < int, int > x : ans ) {
e[x.first].push_back ( x.second );
e[x.second].push_back ( x.first );
in[x.first] ++, in[x.second] --;
}
dfs ( 1, 0 );
return 0;
}