#521. 「LibreOJ β Round #3」绯色 IOI(抵达)
description
solution
因为点的庇护所不能为自身,题目背景在树上,有结论一定是两个相邻点互为庇护所
所以树一定要能两两完美匹配才有解
判断完有解后就是构造解了,用类似拓扑的算法
对于互为庇护所的i,ji,ji,j点,iii向jjj其它儿子连边,jjj同理
庇护所的权值得最小,所以要先入队先从队列里面出来
对于同时在队列里面的点按照编号排序,则是满足了字典序最小的要求
至此,本题被完美解决
code
#include <cstdio>
#include <vector>
#include <queue>
using namespace std;
#define maxn 500005
priority_queue < int, vector < int >, greater < int > > q;
vector < int > G[maxn], R[maxn];
int n;
int f[maxn], d[maxn], ans[maxn];
bool vis[maxn];void dfs( int u, int fa ) {f[u] = fa;for( int i = 0;i < G[u].size();i ++ ) {int v = G[u][i];if( v == fa ) continue;else dfs( v, u );}if( u != 1 && ! vis[u] && ! vis[fa] ) {vis[u] = vis[fa] = 1;for( int i = 0;i < G[fa].size();i ++ )if( G[fa][i] == u ) continue;else R[u].push_back( G[fa][i] ), d[G[fa][i]] ++;for( int i = 0;i < G[u].size();i ++ )if( G[u][i] == fa ) continue;else R[fa].push_back( G[u][i] ), d[G[u][i]] ++;}
}int main() {scanf( "%d", &n );for( int i = 1, u, v;i < n;i ++ ) {scanf( "%d %d", &u, &v );G[u].push_back( v );G[v].push_back( u );}dfs( 1, 0 );for( int i = 1;i <= n;i ++ )if( ! vis[i] ) return ! printf( "-1\n" );for( int i = 1;i <= n;i ++ )if( ! d[i] ) q.push( i );int cnt = 0;while( ! q.empty() ) {int u = q.top(); q.pop();ans[++ cnt] = u;for( int i = 0;i < R[u].size();i ++ ) {int v = R[u][i];d[v] --;if( ! d[v] ) q.push( v );}}for( int i = 1;i <= n;i ++ )printf( "%d ", ans[i] );return 0;
}