【HDOJ】3061 Battle

时间:2022-04-21 14:51:44

Dinic解网络流模板题目。队列用STL就TLE。。。

 /* 3061 */
#include <iostream>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <deque>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <cstring>
#include <climits>
#include <cctype>
#include <cassert>
#include <functional>
#include <iterator>
#include <iomanip>
using namespace std;
//#pragma comment(linker,"/STACK:102400000,1024000") #define sti set<int>
#define stpii set<pair<int, int> >
#define mpii map<int,int>
#define vi vector<int>
#define pii pair<int,int>
#define vpii vector<pair<int,int> >
#define rep(i, a, n) for (int i=a;i<n;++i)
#define per(i, a, n) for (int i=n-1;i>=a;--i)
#define clr clear
#define pb push_back
#define mp make_pair
#define fir first
#define sec second
#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define lson l, mid, rt<<1
#define rson mid+1, r, rt<<1|1 const int INF = 1e9;
const int maxn = ;
const int maxe = ;
int V[maxe], F[maxe], nxt[maxe];
int head[maxn], dis[maxn];
int head_[maxn];
int Q[maxn];
int s, t;
int n, m; void init(int n_) {
memset(head, -, sizeof(head));
s = m = ;
n = n_ + ;
t = n - ;
} void addEdge(int u, int v, int c) {
V[m] = v;
F[m] = c;
nxt[m] = head[u];
head[u] = m++; V[m] = u;
F[m] = ;
nxt[m] = head[v];
head[v] = m++;
} bool bfs() {
int u, v, k;
int l = , r = ; memset(dis, -, sizeof(dis));
dis[s] = ;
Q[r++] = s; while(l < r) {
u = Q[l++];
for (k=head[u]; k!=-; k=nxt[k]) {
v = V[k];
if (F[k] && dis[v]<) {
dis[v] = dis[u] + ;
if (v == t)
return false;
Q[r++] = v;
}
}
} return true;
} int dfs(int u, int a) {
if (u == t)
return a; int v, tmp; for (int& k=head_[u]; k!=-; k=nxt[k]) {
v = V[k];
if (F[k] && dis[v]==dis[u]+ && (tmp=dfs(v, min(a, F[k])))>) {
F[k] -= tmp;
F[k^] += tmp;
return tmp;
}
} return ;
} int Dinic() {
int ret = , tmp; while () {
if (bfs())
break;
memcpy(head_, head, sizeof(head));
while ((tmp = dfs(s, INF))!=)
ret += tmp;
} return ret;
} int main() {
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif int n_, m_;
int u, v;
int tot, ans, x; while (scanf("%d %d", &n_, &m_) != EOF) {
init(n_);
tot = ;
rep(i, , n_+) {
scanf("%d", &x);
if (x > ) {
addEdge(s, i, x);
tot += x;
} else if (x < ) {
addEdge(i, t, -x);
}
}
while (m_--) {
scanf("%d %d", &u, &v);
addEdge(u, v, INF);
}
ans = Dinic();
printf("%d\n", tot-ans);
} #ifndef ONLINE_JUDGE
printf("time = %d.\n", (int)clock());
#endif return ;
}