BZOJ 1491 社交网络(最短路)
对于这道题,如果我们能求出s到t的最短路径数目和s由v到t的最短路径数目,剩下的很好求了。
令dis[i][j]表示i到j的最短路径,dp[i][j]表示i到j的最短路径条数,如果dis[s][v]+dis[v][t]=dis[s][t]。那么必有s由v到t的最短路径条数=dp[s][v]*dp[v][t]。
我们可以进行n次dijkstra求出dis[i][j]。
对于dp数组,考虑dijkstra的过程。如果由v对u的拓展出现dis[u]==dis[v]+w,那么dp[start][u]+=dp[start][v]。
如果由v更新了节点u的最短路径,那么dp[start][u]=dp[start][v]。
# include <cstdio> # include <cstring> # include <cstdlib> # include <iostream> # include <vector> # include <queue> # include <stack> # include <map> # include <set> # include <cmath> # include <algorithm> using namespace std; # define lowbit(x) ((x)&(-x)) # define pi 3.1415926535 # define eps 1e-9 # define MOD 100000007 # define INF 1000000000 # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define bug puts("H"); # define lch p<<1,l,mid # define rch p<<1|1,mid+1,r # define mp make_pair # define pb push_back typedef pair<int,int> PII; typedef vector<int> VI; # pragma comment(linker, "/STACK:1024000000,1024000000") typedef long long LL; int Scan() { int res=0, flag=0; char ch; if((ch=getchar())=='-') flag=1; else if(ch>='0'&&ch<='9') res=ch-'0'; while((ch=getchar())>='0'&&ch<='9') res=res*10+(ch-'0'); return flag?-res:res; } void Out(int a) { if(a<0) {putchar('-'); a=-a;} if(a>=10) Out(a/10); putchar(a%10+'0'); } const int N=105; //Code begin... struct qnode{ int v, c; qnode(int _v=0, int _c=0):v(_v),c(_c){} bool operator<(const qnode &r)const{return c>r.c;} }; struct Edge{ int v, cost; Edge(int _v=0, int _cost=0):v(_v),cost(_cost){} }; vector<Edge>E[N]; LL dp[N][N]; int dis[N][N], dist[N]; bool vis[N]; double ans[N]; priority_queue<qnode>que; void Dijkstra(int n, int start){ mem(vis,0); FOR(i,1,n) dist[i]=INF; dist[start]=0; que.push(qnode(start,0)); dp[start][start]=1; qnode tmp; while (!que.empty()) { tmp=que.top(); que.pop(); int u=tmp.v; if (vis[u]) continue; vis[u]=true; FO(i,0,E[u].size()) { int v=E[u][i].v, cost=E[u][i].cost; if (dist[v]==dist[u]+cost) {dp[start][v]+=dp[start][u]; continue;} if (!vis[v]&&dist[v]>dist[u]+cost) { dist[v]=dist[u]+cost, que.push(qnode(v,dist[v])); dp[start][v]=dp[start][u]; } } } FOR(i,1,n) dis[start][i]=dist[i]; } int main () { int n, m, u, v, w; scanf("%d%d",&n,&m); FOR(i,1,m) scanf("%d%d%d",&u,&v,&w), E[u].pb(Edge(v,w)), E[v].pb(Edge(u,w)); FOR(i,1,n) Dijkstra(n,i); FOR(i,1,n) FOR(j,1,n) { if (i==j) continue; FOR(k,1,n) { if (k==i||k==j) continue; if (dis[j][i]+dis[i][k]==dis[j][k]) ans[i]+=((double)dp[j][i]*dp[i][k])/(dp[j][k]); } } FOR(i,1,n) printf("%.3f\n",ans[i]); return 0; }