【暑假】[基本数据结构]根据BFS与DFS确定树
2016-03-30 17:19
120 查看
UVa10410 Tree Reconstruction
算法:根据BFS构造pos数组以区分关系,在此基础上对DFS序列操作。注:栈中存父结点,栈顶是最优先的父结点。
代码如下:
算法:根据BFS构造pos数组以区分关系,在此基础上对DFS序列操作。注:栈中存父结点,栈顶是最优先的父结点。
代码如下:
1 #include<cstdio> 2 #include<vector> 3 #include<stack> 4 #define FOR(a,b,c) for(int a=(b);a<(c);a++) 5 using namespace std; 6 7 const int maxn= 1000 + 10; 8 9 int pos[maxn]; //BFS中的位置关系 10 vector<int> G[maxn]; 11 12 int main(){ 13 int n; 14 while(scanf("%d",&n)==1){ 15 int x; 16 FOR(i,1,n+1){ 17 scanf("%d",&x); 18 pos[x]=i; 19 G[i].clear(); //G_clear 20 } 21 int root; 22 scanf("%d",&root); 23 stack<int> sta; sta.push(root); 24 int v; 25 FOR(i,1,n){ 26 scanf("%d",&v); 27 for(;;){ 28 int u=sta.top(); 29 if(u==root || pos[u]+1<pos[v]){ //u是v的父结点 30 sta.push(v); 31 G[u].push_back(v); 32 break; //直到找到父结点 33 } 34 else //u和v是兄弟 返回到u的父结点 35 sta.pop(); 36 } 37 } 38 FOR(u,1,n+1){ 39 printf("%d:",u); 40 FOR(j,0,G[u].size()) printf(" %d",G[u][j]); 41 printf("\n"); 42 } 43 } 44 return 0; 45 }
相关文章推荐
- 【暑假】[基本数据结构]根据in_order与post_order构树
- 【暑假】[基本数据结构]基本的数据结构知识点总结梳理
- 【暑假】[实用数据结构]动态连续和查询问题
- 【暑假】[实用数据结构]范围最小值问题(RMQ)
- 【暑假】[实用数据结构]动态范围查询问题
- 【暑假】[实用数据结构]UVa11995 I Can Guess the Data Structure!
- 【暑假】[实用数据结构]UVa11991 Easy Problem from Rujia Liu?
- 【暑假】[实用数据结构]UVAlive 3135 Argus
- 【暑假】[实用数据结构]UVa11997 K Smallest Sums
- 【暑假】[实用数据结构]UVAlive 3644 X-Plosives
- 【暑假】[实用数据结构]UVAlive 3027 Corporative Network
- 【暑假】[实用数据结构]UVAlive 4329 Ping pong
- 【暑假】[实用数据结构]UVa11235 Frequent values
- 【暑假】[实用数据结构]前缀树 Trie
- 【暑假】[实用数据结构]KMP
- netmap分析(3)-原理分析之数据结构关系
- Java数据结构——双端链表
- 《数据结构》 栈代码操作集合
- 数据结构(java语言描述)串与数组——文件加解密
- 常见的数据结构和算法