hihocoder1490 Tree Restoration 模拟

There is a tree of N nodes which are numbered from 1 to N. Unfortunately, its edges are missing so we don't know how the nodes are connected. Instead we know:

1. Which nodes are leaves

2. The distance (number of edges) between any pair of leaves

3. The depth of every node (the root's depth is 1)

4. For the nodes on the same level, their order from left to right

Can you restore the tree's edges with these information? Note if node u is on the left of node vu's parent should not be on the right of v's parent.

hihocoder1490 Tree Restoration 模拟

题意:有一颗树,给出叶子节点有哪些,叶子节点之间互相的距离,每个节点的深度,并且每层给定左右顺序,树边不交叉,要求复原树。

其实就是一个模拟题,我们可以知道,如果同一层两个叶子节点的距离是2,那么他们肯定是兄弟节点,而由于左右顺序给定,叶节点也给定,那么某一层最左边的两个叶子节点的父节点一定是上一层最左边的一个非叶子节点,而父节点和除子树外各节点的距离,其实是子节点和它们距离 - 1。我就能通过子节点得到父节点的距离信息了。

这个思路就可以做模拟了,我们对于最后一层从最左边的叶子节点开始,找到所有它的兄弟,它的距离顺便更新它的父节点的距离,之后父节点就可以当做叶节点了,然后继续操作同层所有的叶节点,寻找到父亲并更新父亲的距离。这样一层一层向上知道第二层就行。

模拟裸题。

 #include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std; const int maxn=;
const int INF=0x3f3f3f3f;
const int mod=1e9+; int n,m,k; int vis[maxn];
int fa[maxn];
int mcnt[maxn];
int M[maxn][maxn];
int Map[maxn][maxn];
int a[maxn]; void update( int l ){
int f = fa[l];
for(int i = ; i <= n ; ++ i ){
if( Map[l][i] != -){
Map[f][i] = Map[i][f] = Map[l][i] - ;
}
}
} int main(){
memset(fa,-,sizeof(fa));
scanf("%d%d%d",&n,&m,&k);
for(int i = ; i <= m ; ++ i){
scanf("%d",&mcnt[i]);
}
for(int i = ; i <= m ; ++ i){
for(int j = ; j <= mcnt[i] ; ++ j){
scanf("%d",&M[i][j]);
}
}
memset(vis,,sizeof(vis));
for(int i = ; i <= k ; ++ i){
scanf("%d",&a[i]);
vis[a[i]] = ;
}
memset(Map,-,sizeof(Map));
for(int i = ; i <= k ; ++ i ){
for(int j = ; j <= k ; ++ j ){
scanf("%d",&Map[a[i]][a[j]]);
}
} for(int l = m ; l > ; -- l ){
int S = l,F = l - ;
int pos1 = ,pos2 = ;
while( pos2 <= mcnt[F] && vis[ M[F][pos2] ] )pos2++;
fa[ M[S][pos1] ] = M[F][pos2];
while( pos1 <= mcnt[S] ){
int l1 = M[S][pos1];
if(pos1 == mcnt[S] ){
update( l1 );
break;
}
else{
int l2 = M[S][pos1+];
if( Map[l1][l2] != ){
update( l1 );
pos2++;
while( pos2 <= mcnt[F] && vis[ M[F][pos2] ] )pos2++;
}
fa[l2] = M[F][pos2];
pos1++;
}
}
}
for(int i = ; i <= n ; ++ i ){
if(fa[i] == - )printf("");
else printf("%d",fa[i]);
if(i==n)printf("\n");
else printf(" ");
}
return ;
}
上一篇:17秋 软件工程 第六次作业 Beta冲刺 Scrum4


下一篇:畅通工程再续 HDU - 1875