三倍经验,三个条件,分别对应了常见的3种模型,第一种是限制每个点只能一次且无交点,我们可以把这个点拆成一个出点一个入点,capacity为1,这样就限制了只选择一次,第二种是可以有交点,但不能有交边,那我们就不需要拆点,限制每条capacity都为1就可以了,第三种直接连,没有限制(
#include<bits/stdc++.h> using namespace std; #define lowbit(x) ((x)&(-x)) typedef long long LL; const int maxm = 1e6+5; const int INF = 0x3f3f3f3f; struct edge{ int u, v, cap, flow, cost, nex; } edges[maxm]; int head[maxm], cur[maxm], cnt, fa[maxm], d[maxm], buf[43][43], num[43][43], ID; bool inq[maxm]; void init() { memset(head, -1, sizeof(head)); } void add(int u, int v, int cap, int cost) { edges[cnt] = edge{u, v, cap, 0, cost, head[u]}; head[u] = cnt++; } void addedge(int u, int v, int cap, int cost) { add(u, v, cap, cost), add(v, u, 0, -cost); } bool spfa(int s, int t, int &flow, LL &cost) { //for(int i = 0; i <= n+1; ++i) d[i] = INF; //init() memset(d, 63, sizeof(d)); memset(inq, false, sizeof(inq)); d[s] = 0, inq[s] = true; fa[s] = -1, cur[s] = INF; queue<int> q; q.push(s); while(!q.empty()) { int u = q.front(); q.pop(); inq[u] = false; for(int i = head[u]; i != -1; i = edges[i].nex) { edge& now = edges[i]; int v = now.v; if(now.cap > now.flow && d[v] > d[u] + now.cost) { d[v] = d[u] + now.cost; fa[v] = i; cur[v] = min(cur[u], now.cap - now.flow); if(!inq[v]) {q.push(v); inq[v] = true;} } } } if(d[t] == INF) return false; flow += cur[t]; cost += 1LL*d[t]*cur[t]; for(int u = t; u != s; u = edges[fa[u]].u) { edges[fa[u]].flow += cur[t]; edges[fa[u]^1].flow -= cur[t]; } return true; } int MincostMaxflow(int s, int t, LL &cost) { cost = 0; int flow = 0; while(spfa(s, t, flow, cost)); return flow; } void run_case() { int m, n; cin >> m >> n; int s = 0, t = 1e6; // first init(); for(int i = m; i < n+m; ++i) for(int j = 1; j <= i; ++j) { num[i][j] = ++ID; cin >> buf[i][j]; addedge(ID<<1, (ID<<1)|1, 1, -buf[i][j]); } for(int i = m; i < n+m-1; ++i) { for(int j = 1; j <= i; ++j) { addedge((num[i][j]<<1)|1, num[i+1][j]<<1, 1, 0); addedge((num[i][j]<<1)|1, num[i+1][j+1]<<1, 1, 0); } } for(int i = 1; i <= m; ++i) addedge(s, num[m][i]<<1, 1, 0); for(int i = 1; i < n+m; ++i) addedge((num[n+m-1][i]<<1)|1, t, 1, 0); LL cost = 0; MincostMaxflow(s, t, cost); cout << -cost << " "; // second init(); for(int i = m; i < n+m-1; ++i) for(int j = 1; j <= i; ++j) { addedge(num[i][j], num[i+1][j], 1, -buf[i+1][j]); addedge(num[i][j], num[i+1][j+1], 1, -buf[i+1][j+1]); } for(int i = 1; i <= m; ++i) addedge(s, num[m][i], 1, -buf[m][i]); for(int i = 1; i < n+m; ++i) addedge(num[n+m-1][i], t, INF, 0); cost = 0, MincostMaxflow(s, t, cost); cout << -cost << " "; // third init(); for(int i = m; i < n+m-1; ++i) for(int j = 1; j <= i; ++j) { addedge(num[i][j], num[i+1][j], INF, -buf[i+1][j]); addedge(num[i][j], num[i+1][j+1], INF, -buf[i+1][j+1]); } for(int i = 1; i <= m; ++i) addedge(s, num[m][i], 1, -buf[m][i]); for(int i = 1; i < n+m; ++i) addedge(num[n+m-1][i], t, INF, 0); cost = 0, MincostMaxflow(s, t, cost); cout << -cost << " "; } int main() { ios::sync_with_stdio(false), cin.tie(0); run_case(); cout.flush(); return 0; }