题意:
求有多少条最短路
解析:
正着求一遍最短路 得dis1 反着求一遍得 dis2 然后 遍历所有的边 如果 dis1[u] + dis2[v] + w == dis1[B], 则说明这是一条最短路边
建网络流的边 容量为1 代表这条边只能走一次
如果是无向边一次就好了, 就是挑出来所有符合条件的边
------------------------------
为什么我的代码的规范上边和下边不一样。。。。。因为。。。emm。。。这是我半年前做的题。。然而那时候只会EK 当然T了。。会了Dinic后。。就忘了这题了。。。今天发现 啊啊啊啊啊。。。然后就改了一下代码。。。。我竟然和半年前做一样的题。。。我真是菜啊。。。。。。
#include <iostream> #include <cstring> #include <cstdio> #include <queue> #include <cmath> #include <vector> #define mem(a,b) memset(a,b,sizeof(a)) using namespace std; const int maxn = 1e3 + 10, INF = 0xfffffff, maxm = 100010; typedef long long LL; int n,m, cnt, s, t; int head[maxn], d[maxn], vis[maxn], dis1[maxn], dis2[maxn], head1[maxn], cur[maxn]; int from[maxm], to[maxm], w[maxm]; struct edge { int u, v, c, next; }Edge[maxm << 1]; void add_(int u, int v, int c) { Edge[cnt].u = u; Edge[cnt].v = v; Edge[cnt].c = c; Edge[cnt].next = head1[u]; head1[u] = cnt++; } void add_edge(int u, int v, int c) { add_(u, v, c); add_(v, u, 0); } bool bfs() { mem(d, 0); queue<int> Q; Q.push(s); d[s] = 1; while(!Q.empty()) { int u = Q.front(); Q.pop(); for(int i = head1[u]; i != -1; i = Edge[i].next) { edge e = Edge[i]; if(!d[e.v] && e.c > 0) { d[e.v] = d[u] + 1; Q.push(e.v); if(e.v == t) return 1; } } } return d[t] != 0; } int dfs(int u, int cap) { int ret = 0; if(u == t || cap == 0) return cap; for(int &i = cur[u]; i != -1; i = Edge[i].next) { edge e = Edge[i]; if(d[e.v] == d[u] + 1 && e.c > 0) { int V = dfs(e.v, min(e.c, cap)); Edge[i].c -= V; Edge[i ^ 1].c += V; ret += V; cap -= V; if(cap == 0) break; } } if(cap > 0) d[u] = -1; return ret; } int Dinic() { int ans = 0; while(bfs()) { memcpy(cur, head1, sizeof(head1)); ans += dfs(s, INF); } return ans; } struct node { int u, v, w, next; }Node[maxn * 10]; void add(int u,int v,int w,int i) { Node[i].u = u; Node[i].v = v; Node[i].w = w; Node[i].next = head[u]; head[u] = i; } void spfa(int s) { for(int i = 0; i < maxn; i++) d[i] = INF; queue<int> Q; d[s] = 0; mem(vis,0); Q.push(s); vis[s] = 1; while(!Q.empty()) { int u = Q.front();Q.pop(); vis[u] = 0; for(int i=head[u]; i!=-1; i=Node[i].next) { node e = Node[i]; if(d[e.v] > d[u] + e.w) { d[e.v] = d[u] + e.w; if(!vis[e.v]) { Q.push(e.v); vis[e.v] = 1; } } } } } int main() { int T,A,B; scanf("%d",&T); while(T--) { mem(Node,0); mem(head,-1); mem(head1, -1); cnt = 0; scanf("%d%d",&n,&m); for(int i=0; i<m; i++) { scanf("%d%d%d",&from[i],&to[i],&w[i]); add(from[i],to[i],w[i],i); } scanf("%d%d",&A,&B); s = A, t = B; spfa(A); mem(Node,0); for(int i=1; i<=n; i++) dis1[i] = d[i]; mem(head,-1); for(int i=0; i<m; i++) add(to[i],from[i],w[i],i); spfa(B); for(int i=1; i<=n; i++) dis2[i] = d[i]; for(int i=0; i<m; i++) if(from[i] != to[i] && dis1[from[i]] + dis2[to[i]] + w[i] == dis1[B]) add_edge(from[i],to[i],1); printf("%d ",Dinic()); } return 0; }