1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| #include <bits/stdc++.h> using namespace std; const int maxn = 105; const int maxm = 1e5; const int inf = 0x3f3f3f3f;
struct Edge { int v,c,next,cost; } edge[maxm]; int n,tot,sink,source,mincost; int num[maxn],x[maxn]; int head[maxn],dep[maxn];
void add(int u,int v,int c,int cost) { edge[tot].v=v; edge[tot].c=c; edge[tot].cost=cost; edge[tot].next=head[u]; head[u]=tot++; } void addedge(int u,int v,int c,int cost) { add(u,v,c,cost); add(v,u,0,-cost); }
int dist[maxn],pre[maxn]; bool vis[maxn];
bool spfa() { queue<int> que; memset(dist,inf,sizeof dist); memset(vis,0,sizeof vis); dist[source] = 0; que.push(source); while (!que.empty()) { int cur = que.front(); que.pop(); vis[cur] = 0; for (int i=head[cur];i!=-1;i=edge[i].next) { int to = edge[i].v; if (edge[i].c>0 && dist[to]>dist[cur]+edge[i].cost) { dist[to] = dist[cur] + edge[i].cost; if (!vis[to]) { vis[to] = 1; que.push(to); } } } } return dist[sink]!=inf; }
int dfs(int u,int delta) { if (u == sink) return delta; vis[u] = 1; int flow = 0; for (int i=head[u];i!=-1;i=edge[i].next) { int to = edge[i].v; if (!vis[to] && edge[i].c>0 && dist[to]==dist[u]+edge[i].cost) { int temp = dfs(to,min(delta-flow,edge[i].c)); if (temp) { mincost += (edge[i].cost * temp); edge[i].c -= temp; edge[i^1].c += temp; flow += temp; } } } vis[u] = 0; return flow; }
int Dinic() { int maxflow=0; while (spfa()) { while (1) { int temp = dfs(source,inf); if (!temp) break; maxflow += temp; } } return maxflow; }
int main() { memset(head,-1,sizeof head); cin >> n; int avg = 0; for (int i=1; i<=n; ++i) { cin >> num[i]; avg += num[i]; } avg = avg / n; source = 0; sink = n+1; for (int i=1; i<=n; ++i) x[i] = num[i] - avg; for (int i=1; i<=n; ++i) { if (x[i] > 0) addedge(source,i,x[i],0); if (x[i] < 0) addedge(i,sink,-x[i],0); } for (int i=1; i<=n; ++i) { if (i!=1) addedge(i,i-1,inf,1); if (i!=n) addedge(i,i+1,inf,1); } addedge(1,n,inf,1); addedge(n,1,inf,1); int maxflow = Dinic(); cout << mincost << endl; return 0; }
|