典型的树DFS模型
题目:
时间限制 1000 ms 内存限制 65536 KB Special Judge
题目描述
有一棵多叉树T,你在树根处,宝藏在某一叶子节点L。现在你沿着树枝向叶子方向走去,从不回头,如果遇到树叉节点,你等概率地挑选一个分支继续走。请问,在给定T,L的情况下,你有多大概率拿到宝藏?
输入格式
第一行,整数N,M,L(1< N< 1000,0< M< 1000,0< L< N),分别代表树T上的节点数、树枝的个数,宝藏所在节点。树根为0号结点。
然后有M行,每行两个整数A,B(0≤ A,B< N)代表从节点A到节点B有一条树枝。可以假设节点A总是更靠近树根。
输出格式
所求的概率,输出四舍五入到6位小数,然后换行。
输入样例
6 5 5
0 1
1 3
0 2
2 4
2 5
输出样例
0.250000
#include <iostream>
#include <cstdio>
#include <vector>
#define MAXSIZE 1010
using namespace std;
typedef struct Node{
int data;//必要时可设置父节点指针来方便查询父节点
vector<int> sonList;
bool turnOn;
Node(){//initiate automatically except data
initNode();
}
void initNode(){
turnOn=false;
sonList.clear();
}
}*Tree;
Node treeList[MAXSIZE];
int cursor;
int n,m,l;
bool haveFind;
//按序分配结点
int createNode(int data){//return the index of new node
if (cursor+1==MAXSIZE)
return -1;//failed
int nowP=cursor;
cursor++;
// treeList[nowP].initNode();
treeList[nowP].turnOn=true;
treeList[nowP].data=data;
return nowP;
}
//按照指定下标分配结点
int createNode(int data,int index){//return the index of new node
// treeList[nowP].initNode();
treeList[index].turnOn=true;
treeList[index].data=data;
return index;
}
void freeNode(int index){
treeList[index].initNode();
}
void freeTree(int index){//postOrder
if (index!=-1){
//traverse
Node &nowN=treeList[index];
for (int i=0;i<nowN.sonList.size();i++){
freeTree(nowN.sonList[i]);
}
//visit
freeNode(index);
}
}
void preOrder(int root,double nowProb){
if (root!=-1){
//visit
Node &nowNode=treeList[root];
if (root==l){
printf("%.6lf\n",nowProb);
haveFind=true;
}
//traverse
if (haveFind==false){
for(int i=0;i<nowNode.sonList.size();i++)
preOrder(nowNode.sonList[i],nowProb/nowNode.sonList.size());
}
}
}
int main(){
int father,son;
while (scanf("%d",&n)!=EOF){
//initiate
for (int i=0;i<MAXSIZE;i++){
treeList[i].initNode();
}
haveFind=false;
//input
scanf("%d%d",&m,&l);
for (int i=0;i<m;i++){
scanf("%d%d",&father,&son);
createNode(father,son);
treeList[father].sonList.push_back(son);
}
//search
preOrder(0,1.0);
//output
}
return true;
}