标签:io os ar for sp c amp ad ef
11.1.1:有根树转无根树
#include<iostream>
#include<cstring>
#include<vector>
#include<cstdio>
#define maxn 1000
using namespace std;
vector<int> G[maxn];
int p[maxn];
void read_tree()
{
int n,u,v;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d%d",&u,&v);
G[u].push_back(v); //与邻接表异曲同工
G[v].push_back(u);
}
}
void dfs(int root,int fa)
{
int d=G[root].size();
for(int i=0;i<d;i++)
{
int v=G[root][i];
if(v!=fa)
dfs(v,p[v]=root);
}
}
int main()
{
for(int i=0;i<maxn;i++)
G[i].clear();
memset(p,-1,sizeof p);
read_tree();
dfs(1,-1); //p[root]=-1;
return 0;
}
dfs遍历图,
标签:io os ar for sp c amp ad ef
原文地址:http://blog.csdn.net/code_or_code/article/details/39341453