bzoj 1415: [Noi2005]聪聪和可可
直接上记忆化搜索
#include<queue> #include<cstdio> #include<algorithm> using namespace std; int read_p,read_ca; inline int read(){ read_p=0;read_ca=getchar(); while(read_ca<'0'||read_ca>'9') read_ca=getchar(); while(read_ca>='0'&&read_ca<='9') read_p=read_p*10+read_ca-48,read_ca=getchar(); return read_p; } struct na{ int y,ne; }b[10001]; queue <int> q; int a,bb; int n,m,l[3001],r[3001],ru[3001],num=0; int ne[1001][1001],dis[1001][1001]; double jy[1001][1001]; bool bo[1001][1001]; const int INF=1e9; inline void add(int x,int y){ num++; if (!l[x]) l[x]=num;else b[r[x]].ne=num; b[num].y=y;r[x]=num; } inline void bfs(int x){ for (int i=1;i<=n;i++) dis[x][i]=INF; dis[x][x]=0;ne[x][x]=x; for (int i=l[x];i;i=b[i].ne) dis[x][b[i].y]=1,ne[x][b[i].y]=b[i].y,q.push(b[i].y); while (!q.empty()){ int k=q.front();q.pop(); for (int i=l[k];i;i=b[i].ne) if (dis[x][b[i].y]>dis[x][k]+1) dis[x][b[i].y]=dis[x][k]+1,ne[x][b[i].y]=ne[x][k],q.push(b[i].y);else if (dis[x][b[i].y]==dis[x][k]+1&&ne[x][b[i].y]>ne[x][k]) ne[x][b[i].y]=ne[x][k],q.push(b[i].y); } } inline double dfs(int a,int bb){ if (a==bb) return 0.0; if (bo[a][bb]) return jy[a][bb]; bo[a][bb]=1; double ans=0.0; int aa=ne[ne[a][bb]][bb]; if (aa==bb) return jy[a][bb]=1.0; int u=1; for (int i=l[bb];i;i=b[i].ne) ans+=dfs(aa,b[i].y),u++; ans+=dfs(aa,bb); ans=1.0/u*ans+1.0; return jy[a][bb]=ans; } int main(){ int i,j,x,y; n=read();m=read(); a=read();bb=read(); for (i=1;i<=m;i++) x=read(),y=read(),add(x,y),add(y,x); for (int i=1;i<=n;i++) bfs(i); printf("%.3lf\n",dfs(a,bb)); return 0; }