标签:dp
对于50%的数据,1≤N≤50。
第一道概率dp的题,首先要对每一个点bfs一下, 预处理出从i到j的最短路上,i下一步会走到的点p[i][j];
设dp[i][j]表示聪聪在i,可可在j时聪聪可以吃到可可平均要走的次数
如果p[i][j] == j || p[ p[i][j] ][j] == j,则dp[i][j] = 1,
如果i == j dp[i][j] = 0;
其他情况: 令u = p[ p[i][j] ][j]
dp[i][j] = ((dp[u][j] + 1)+ sigma(dp[u][k] (k与点j相连) + 1)) / (deg[j] + 1)
deg[j] 是点j的度数
#include <map> #include <set> #include <list> #include <queue> #include <stack> #include <vector> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <iostream> #include <algorithm> using namespace std; const int N = 1010; int n, m; int p[N][N]; int dist[N]; double dp[N][N]; int deg[N]; int head[N]; int tot; struct node { int next; int to; }edge[N << 2]; void addedge(int from, int to) { edge[tot].to = to; edge[tot].next = head[from]; head[from] = tot++; } void short_distance() { queue <int> qu; for (int i = 1; i <= n; ++i) { while (!qu.empty()) { qu.pop(); } memset (dist, 0x3f3f3f3f, sizeof(dist)); dist[i] = 0; qu.push(i); p[i][i] = i; while (!qu.empty()) { int u = qu.front(); qu.pop(); for (int j = head[u]; ~j; j = edge[j].next) { int v = edge[j].to; if (dist[v] > dist[u] + 1 ||(u < p[v][i] && dist[v] == dist[u] + 1)) { p[v][i] = u; dist[v] = dist[u] + 1; qu.push(v); } } } } } double dfs(int i, int j) { if (i == j) { return dp[i][j] = 0; } if (p[i][j] == j || p[ p[i][j] ][j] == j) { return dp[i][j] = 1; } if (dp[i][j] != -1) { return dp[i][j]; } double cur = 0; int u = p[ p[i][j] ][j]; cur = dfs(u, j) + 1; //可可留在原地 for (int k = head[j]; ~k; k = edge[k].next) { cur += dfs(u, edge[k].to) + 1; } cur /= (deg[j] + 1); return dp[i][j] = cur; } int main() { int s, e; while (~scanf("%d%d", &n, &m)) { scanf("%d%d", &s, &e); int u, v; memset (head, -1, sizeof(head)); memset (deg, 0, sizeof(deg)); tot = 0; for (int i = 1; i <= m; ++i) { scanf("%d%d", &u, &v); addedge(u, v); addedge(v, u); deg[u]++; deg[v]++; } for (int i = 1; i <= n; ++i) { dp[i][i] = 0; for (int j = 1; j <= n; ++j) { if (i == j) { continue; } dp[i][j] = -1; } } short_distance(); dfs(s, e); printf("%.3f\n", dp[s][e]); } return 0; }
标签:dp
原文地址:http://blog.csdn.net/guard_mine/article/details/42009751