洛谷P3377 【模板】左偏树(可并堆)
30分代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
inline int read(){
int x = 0,tmp = 1;char ch = getchar();
while( ch < '0' || ch > '9' ) {if ( ch == '-' ) tmp = -1; ch = getchar();}
while( ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar(); }
return x * tmp;
}
inline void write( int k ) {
if ( k < 0 ) { putchar( '-' ); k = -k;}
if ( k > 9 ) write( k / 10 );
putchar( k % 10 + '0' );
}
struct tree{
int l, r, v, dis, f;
} heap[110000];
bool hash[110000];
inline int find( int x ) {
return heap[x].f == x ? x : find( heap[x].f );
}
inline int merge( int a, int b ) {
if ( heap[a].v > heap[b].v || a > b && heap[a].v == heap[b].v) swap( a, b );
if( a == 0 ) return b;
heap[a].r = merge( heap[a].r, b );
heap[heap[a].r].f = a;
if( heap[heap[a].l].dis < heap[heap[a].r].dis ) swap( heap[a].l, heap[a].r );
//if( heap[a].r == 0 ) heap[a].dis = 0; else
heap[a].dis = heap[heap[a].r].dis + 1;
return a;
}
inline int pop( int x ){
int l = heap[x].l, r = heap[x].r;
heap[l].f = l;
heap[r].f = r;
heap[x].l = heap[x].r = heap[x].dis = 0;
return merge( l ,r );
}
int main() {
int N = read(), M = read();
for( int i=1; i<=N ; ++i) {
heap[i].v = read();
heap[i].l = heap[i].r = heap[i].dis = 0;
heap[i].f = i;
}
for( int i=1; i<=M; ++i) {
int flag = read();
if( flag == 1 ) {
int x = read(), y = read();
int findx = find ( x ), findy = find ( y );
if ( findx == findy ) continue;
merge( findx, findy );
} else if( flag == 2 ) {
int x = read();
int findx = find( x );
if ( !(hash[x] || hash[findx]) ) {
write( heap[findx].v );
putchar( '\n' );
pop( findx );
hash[findx] = 1;
} else printf( "-1\n" );
}
}
return 0;
}
struct Point {
int to, next;
} edge[210000];
int head[110000], inde[110000], idx = 0, f[110000];
queue<int> Q;
inline void ade( int u, int v ) {
inde[v] ++;
edge[++ idx].to = v;
edge[idx].next = head[u];
head[u] = idx;
}
int main(){
memset( f, 0, sizeof( f ) );
memset( head, -1, sizeof( head) );
int N = read(), M = read();
for( int i = 1 ; i <= M ; ++ i ) {
int x = read(), y = read();
ade( x, y );
}
for( int i = 1 ; i <= N ; ++ i )
if( !inde[i] ) {
Q.push( i );
f[i] = 1;
}
while( !Q.empty() ) {
int u = Q.front();
Q.pop();
for( int i = head[u] ; i != -1 ; i = edge[i].next ) {
int v = edge[i].to;
inde[v] --;
f[v] = max( f[v], f[u] + 1 );
if( !inde[v] ) Q.push( v );
}
}
for( int i = 1 ; i <= N ; ++ i ) {
write( f[i] );
putchar( '\n' );
}
return 0;
}