2750: [HAOI2012]Road
题目:
C国有n座城市,城市之间通过m条单向道路连接。一条路径被称为最短路,当且仅当不存在从它的起点到终点的另外一条路径总长度比它小。两条最短路不同,当且仅当它们包含的道路序列不同。我们需要对每条道路的重要性进行评估,评估方式为计算有多少条不同的最短路经过该道路。
算法:
我博客里以前有过这种类型的题目,就是理解最短路的本质。是bnu上的一题,感兴趣的可以在我博客图论分类里找到。
这题,也是求经过每条边的最短路方案数。则对每条边进行判断就可以了。
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
typedef pair<int,int> P;
inline int read(){
int x = 0,f = 1; char ch = getchar();
while(ch < '0'||ch > '9'){if(ch == '-')f=-1;ch = getchar();}
while(ch >= '0'&&ch <= '9'){x = x * 10 + ch -'0';ch = getchar();}
return x*f;
}
//
const int INF = 1 << 25;
const int MOD = 1000000007;
const int MAXN = 1500 + 10;
struct Edge{
int to,cost,next;
Edge(){};
Edge(int _to,int _cost,int _next)
:to(_to),cost(_cost),next(_next){};
}edge[5005];
int top,head[5005];
int pre[MAXN],d[MAXN];
LL ans[5005],a[5005],b[5005];
int n,m;
void addEdge(int u,int v,int w){
edge[++top].to = v; edge[top].cost = w;
edge[top].next = head[u]; head[u] = top;
}
void dijkstra(int s){
priority_queue<P,vector<P>,greater<P> > Q;
for(int i = 1;i <= n;++i) d[i] = INF;
d[s] = 0;
Q.push(P(0,s));
int v,t = 0;
while(!Q.empty()){
P u = Q.top(); Q.pop();
int x = u.second;
if(d[x] != u.first) continue;
pre[++t] = x;
for(int i = head[x];~i;i = edge[i].next){
v = edge[i].to;
if(d[v] > d[x] + edge[i].cost){
d[v] = d[x] + edge[i].cost;
Q.push(make_pair(d[v],v));
}
}
}
memset(a,0,sizeof(a)); a[s] = 1;
memset(b,0,sizeof(b));
for(int i = 1;i <= t;++i)
b[pre[i]] = 1;
//从前往后走
for(int i = 1;i <= t;++i){
for(int j = head[pre[i]];~j;j = edge[j].next){
v = edge[j].to;
if(d[pre[i]] + edge[j].cost == d[v])
a[v] = (a[v] + a[pre[i]]) % MOD;
}
}
//从后往前走
for(int i = t;i >= 1;--i){
for(int j = head[pre[i]];~j;j = edge[j].next){
v = edge[j].to;
if(d[pre[i]] + edge[j].cost == d[v])
b[pre[i]] = (b[v] + b[pre[i]]) % MOD;
}
}
for(int i = 1;i <= n;++i){
for(int j = head[i];~j;j = edge[j].next){
v = edge[j].to;
if(d[i] + edge[j].cost == d[v])
ans[j] = (ans[j] + a[i] * b[v]%MOD) % MOD;
}
}
}
int main()
{
n = read(); m = read();
int x,y,w;
top = 0;
memset(head,-1,sizeof(head));
for(int i = 0;i < m;++i){
x = read(); y = read(); w = read();
addEdge(x,y,w);
}
for(int i = 1;i <= n;++i) dijkstra(i);
for(int i = 1;i <= m;++i)
printf("%lld\n",ans[i]%MOD);
return 0;
}