大意不再赘述。
思路:与POJ 2112 有很多相似的地方,其实都是二分枚举距离,Floyd预处理,然后网络流判断可行性,二分枚举距离时WA了许多次,因为中间值d[i][j]超INT了,但我还知道怎样离散化距离,如果知道的话,就不会WA许多次了,还有d[i][j]初始化时,需要初始为MAX_ = 99999999999999,虽然编译器上弄不出来,但OJ过了。
还有,如果单纯的用Dinic会超时的,我们需要优化一下,我们可以离散化距离或者删除孤立边(如果<s,u>以及<u,v>的容量为0,即P[i] == 0 || C[i] == 0,那么我们就可以删除<u,v>这段孤立边)
(顺带说下,POJ上我定义为long long 型,输入用%I64d,也过了,好小的错误,在DUT上就果断WA)
#include <iostream> #include <cstdlib> #include <cstdio> #include <cstring> #include <string> using namespace std; typedef long long LL; const int MAXN = 10001; const int MAXM = 1000010; const int INF = 0x3f3f3f3f; const LL MAX_ = 99999999999999; struct Edge { int v, f; int next; }edge[MAXM]; int n, m; int cnt; int totP; int s, t; int first[MAXN], level[MAXN]; LL d[MAXN][MAXN]; int P[MAXN], C[MAXN]; LL MaxR; void init() { cnt = 0; memset(first, -1, sizeof(first)); } void Floyd() { for(int k = 1; k <= n; k++) for(int i = 1; i <= n; i++) if(d[i][k] != MAX_) for(int j = 1; j <= n; j++) d[i][j] = min(d[i][j], d[i][k] + d[k][j]); } void read_graph(int u, int v, int f) { edge[cnt].v = v, edge[cnt].f = f; edge[cnt].next = first[u], first[u] = cnt++; edge[cnt].v = u, edge[cnt].f = 0; edge[cnt].next = first[v], first[v] = cnt++; } int bfs(int s, int t) { int q[MAXN]; memset(level, 0, sizeof(level)); level[s] = 1; int front = 0, rear = 1; q[front] = s; while(front < rear) { int x = q[front++]; if(x == t) return 1; for(int e = first[x]; e != -1; e = edge[e].next) { int v = edge[e].v, f = edge[e].f; if(!level[v] && f) { level[v] = level[x] + 1; q[rear++] = v; } } } return 0; } int dfs(int u, int maxf, int t) { if(u == t) return maxf; int ret = 0; for(int e = first[u]; e != -1; e = edge[e].next) { int v = edge[e].v, f = edge[e].f; if(level[v] == level[u] + 1 && f) { int Min = min(maxf-ret, f); f = dfs(v, Min, t); edge[e].f -= f; edge[e^1].f += f; ret += f; if(ret == maxf) return ret; } } return ret; } int Dinic(int s, int t) { int ans = 0; while(bfs(s, t)) ans += dfs(s, INF, t); return ans; } void read_case() { totP = 0; MaxR = 0; s = 0, t = 2*n+1; for(int i = 1; i <= n; i++) { scanf("%d%d", &P[i], &C[i]); totP += P[i]; } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { d[i][j] = (i == j)? 0:MAX_; } } while(m--) { int u, v; LL w; scanf("%d%d%lld", &u, &v, &w); MaxR += w; if(d[u][v] > w) { d[u][v] = d[v][u] = w; } } Floyd(); } void build(LL mid) { init(); for(int i = 1; i <= n; i++) if(P[i]) { read_graph(s, i, P[i]); } for(int i = 1; i <= n; i++) if(C[i]) { read_graph(i+n, t, C[i]); } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(d[i][j] <= mid && C[j]) //删除孤立边 { read_graph(i, j+n, INF); } } } } void solve() { read_case(); int flag = 0; LL x = 0, y = MaxR+1; while(x <= y) { LL mid = x+(y-x)/2; build(mid); int ans = Dinic(s, t); if(ans >= totP) { y = mid-1; flag = 1; } else x = mid+1; } printf(flag? "%lld\n":"-1\n", x); } int main() { while(~scanf("%d%d", &n, &m)) { solve(); } return 0; }