BZOJ1415【概率DP】

/* I will wait for you */

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <string>
#define make make_pair
#define fi first
#define se second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
typedef map<int, int> mii;

const int maxn = 1010;
const int maxm = 1010;
const int maxs = 26;
const int inf = 0x3f3f3f3f;
const int P = 1000000007;
const double error = 1e-9;

inline ll read()
{
	ll x = 0, f = 1;
	char ch = getchar();
	while (ch < '0' || ch > '9')
		  f = (ch == '-' ? -1 : 1), ch = getchar();
	while (ch >= '0' && ch <= '9')
	 	  x = x * 10 + ch - '0', ch = getchar();
	return x * f;
}

struct edge
{
	int v, next;
} e[2 * maxn];

int n, m, cnt, s, t, head[maxn], q[maxn], num[maxn], dis[maxn][maxn], next[maxn][maxn];
double step[maxn][maxn];

void insert(int u, int v)
{
	num[u]++, num[v]++;
	e[cnt] = (edge) {v, head[u]}, head[u] = cnt++;
	e[cnt] = (edge) {u, head[v]}, head[v] = cnt++;
}

void bfs(int s)
{
	memset(dis[s], -1, sizeof dis[s]);
	
	dis[s][s] = 0, q[0] = s;
	
	int l = 0, r = 1;
	
	while (l != r) {
		int u = q[l++];
		for (int i = head[u]; i != -1; i = e[i].next) {
			int v = e[i].v;
			if (dis[s][v] == -1)
				dis[s][v] = dis[s][u] + 1, q[r++] = v;
		}
	}
}

void dp(int s ,int t)
{
	if (step[s][t] != -1)
		return;
	
	int tmp = next[next[s][t]][t];
	double sum = (dp(tmp, t), step[tmp][t]);
	
	for (int i = head[t]; i != -1; i = e[i].next) {
		int v = e[i].v;
		dp(tmp, v), sum += step[tmp][v];
	}
	
	step[s][t] = (double) sum / (double) (num[t] + 1) + 1;
}	

int main()
{
	n = read(), m = read(), s = read(), t = read();
	
	memset(head, -1, sizeof head);
	for (int i = 1; i <= m; i++)
		insert(read(), read());
		
	for (int i = 1; i <= n; i++)
		bfs(i);
	
	for (int u = 1; u <= n; u++)
		for (int v = 1; v <= n; v++) {
			next[u][v] = u;
			for (int i = head[u]; i != -1; i = e[i].next) {
				int p = e[i].v;
				if (dis[p][v] < dis[next[u][v]][v] || 
					dis[p][v] == dis[next[u][v]][v] && p < next[u][v])
					next[u][v] = p;
			}
		}
	
	for (int i = 1; i <= n; i++)
		for (int j = 1; j <= n; j++) {
			if (i == j)
				step[i][j] = 0;
			else if (next[i][j] == j || next[next[i][j]][j] == j)
				step[i][j] = 1;
			else
				step[i][j] = -1;
		}
	
	dp(s, t), printf("%.3lf\n", step[s][t]);
	
	return 0;
}

你可能感兴趣的:(BZOJ1415【概率DP】)