题意:以1为起点,每次走任意一条路,而且走每条路的概率都随机而且每次走时只会走向未走过的城市。同时,每条路的长度均为1。问:行走路程的期望值是多少?
思路:需要注意的是到达了某一个点时,走每一条可走的路的概率相同而不是最终停在每个终点的概率相同。直接遍历整个图,同时做出相应的计算即可。
AC代码:
#include<iostream>
#include<cstring>
#include<vector>
#define MAX 100005
using namespace std;
bool vis[MAX];
vector<int> G[MAX];
void DFS(int now,double & ans,double val)
{
vis[now] = true;
int size_now = G[now].size();
if(size_now > 1 || (now == 1 && size_now > 0)) ans += val; //需要注意当前点为1的情况。
else return ;
for(int j = 0; j < size_now; j++){
int next = G[now][j];
if(!vis[next]){
if(now == 1)
DFS(next,ans,val/size_now);
else
DFS(next,ans,val/(size_now - 1));
}
}
return ;
}
int main( )
{
int n;
cin >> n;
memset(vis,false,sizeof(vis));
int u,v;
for(int j = 1; j < n; j++)
cin >> u >> v,G[u].push_back(v),G[v].push_back(u);
double ans;
DFS(1,ans,1);
printf("%.10lf\n",ans);
}