【TJOI2015】線性代數
阿新 • • 發佈:2019-01-15
stdin read \n min std ear while sdi line
題面
題解
要求的是
\[
\sum_{i=1}^n\sum_{j=1}^na_ia_jb_{i,j} - \sum_{i=1}^na_ic_i
\]
可以看出這是一個最大權閉合子圖問題
代碼
#include<cstdio> #include<cstring> #include<cctype> #include<algorithm> #define RG register #define file(x) freopen(#x".in", "r", stdin);freopen(#x".out", "w", stdout); #define clear(x, y) memset(x, y, sizeof(x)) inline int read() { int data = 0, w = 1; char ch = getchar(); while(ch != '-' && (!isdigit(ch))) ch = getchar(); if(ch == '-') w = -1, ch = getchar(); while(isdigit(ch)) data = data * 10 + (ch ^ 48), ch = getchar(); return data * w; } const int N(510), maxn(3000010), INF(0x3f3f3f3f); struct edge { int next, to, cap; } e[maxn << 1]; int head[maxn], e_num = -1, n, q[maxn], tail, lev[maxn], cur[maxn]; int S, T, id_b[N][N], id_c[N], idcnt, ans; inline void add_edge(int from, int to, int cap) { e[++e_num] = (edge) {head[from], to, cap}; head[from] = e_num; e[++e_num] = (edge) {head[to], from, cap}; head[to] = e_num; } int bfs() { clear(lev, 0); q[tail = lev[S] = 1] = S; for(RG int i = 1; i <= tail; i++) { int x = q[i]; for(RG int j = head[x]; ~j; j = e[j].next) { int to = e[j].to; if(lev[to] || (!e[j].cap)) continue; q[++tail] = to, lev[to] = lev[x] + 1; } } return lev[T]; } int dfs(int x, int f) { if(x == T || (!f)) return f; int ans = 0, cap; for(RG int &i = cur[x]; ~i; i = e[i].next) { int to = e[i].to; if(e[i].cap && lev[to] == lev[x] + 1) { cap = dfs(to, std::min(f - ans, e[i].cap)); e[i].cap -= cap, e[i ^ 1].cap += cap, ans += cap; if(ans == f) break; } } return ans; } inline int Dinic() { int ans = 0; while(bfs()) { for(RG int i = S; i <= T; i++) cur[i] = head[i]; ans += dfs(S, INF); } return ans; } int main() { #ifndef ONLINE_JUDGE file(cpp); #endif clear(head, -1); n = read(); S = ++idcnt; for(RG int i = 1; i <= n; i++) for(RG int j = 1; j <= n; j++) id_b[i][j] = ++idcnt; for(RG int i = 1; i <= n; i++) id_c[i] = ++idcnt; T = ++idcnt; for(RG int i = 1, x; i <= n; i++) for(RG int j = 1; j <= n; j++) ans += (x = read()), add_edge(S, id_b[i][j], x), add_edge(id_b[i][j], id_c[i], INF), add_edge(id_b[i][j], id_c[j], INF); for(RG int i = 1, x; i <= n; i++) x = read(), add_edge(id_c[i], T, x); printf("%d\n", ans - Dinic()); return 0; }
【TJOI2015】線性代數