用网络流解决一类线性规划问题

用网络流求解线性规划问题

这类问题有单纯性算法
今天主要学习一下用网络流的求解

bzoj 1061

题解
注意体会其中的连边的含义

ac code

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
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e4+10;
const int maxm = 100000+10;
const int INF = 0x3f3f3f3f;
int s, t, n, m;
struct Edge{
int v, cost, cap, next, flow;
}edge[maxm];
int head[maxn];
int pre[maxn];//记录的是哪一条边的编号
int tot;
int dis[maxn];
bool vis[maxn];
void init(){
memset(pre, -1, sizeof(pre));
memset(head, -1, sizeof(head));
tot = 0;
}
void add_edge(int u, int v, int weight, int price){
edge[tot].v = v;
edge[tot].cost = price;
edge[tot].cap = weight;
edge[tot].flow = 0;
edge[tot].next = head[u];
head[u] = tot++;
edge[tot].v = u;
edge[tot].cost = -1*price;
edge[tot].cap = 0;
edge[tot].flow = 0;
edge[tot].next = head[v];
head[v] = tot++;
}
bool SPFA(int s, int t){
for(int i=0; i<maxn; i++) dis[i] = INF;
dis[s] = 0;
memset(vis, 0, sizeof(vis));
memset(pre, -1, sizeof(pre));
queue<int> q;
while(!q.empty()) q.pop();
q.push(s);
vis[s] = true;
while(!q.empty()){
int u = q.front();
q.pop();
vis[u] = false;
for(int i=head[u]; ~i; i=edge[i].next){
int v = edge[i].v;
if(edge[i].cap>edge[i].flow && dis[v]>dis[u]+edge[i].cost){
dis[v] = dis[u]+edge[i].cost;
pre[v] = i;
if(!vis[v]){
q.push(v);
vis[v] = true;
}
}
}
}
if(pre[t] == -1) return false;
return true;
}
int min_cost_max_flow(int s, int t, int &min_cost){
int flow = 0;
while(SPFA(s, t)){
int Min = INF;
for(int i = pre[t]; ~i; i = pre[edge[i^1].v]){
if(Min>edge[i].cap-edge[i].flow){
Min = edge[i].cap - edge[i].flow;
}
}
for(int i=pre[t]; ~i; i = pre[edge[i^1].v]){
//cout<<edge[i^1].v<<" ";
edge[i].flow += Min;
edge[i^1].flow -= Min;
min_cost += edge[i].cost*Min;
}
flow += Min;
}
return flow;
}
int a[maxn];
int main(){
ios::sync_with_stdio(false);
init();
int x, y,z;
scanf("%d%d" , &n , &m) , s = 0 , t = n + 2;
for(int i = 1 ; i <= n ; i ++ ) scanf("%d" , &a[i]) , add_edge(i + 1 , i , INF , 0);
for(int i = 1 ; i <= m ; i ++ ) scanf("%d%d%d" , &x , &y , &z) , add_edge(x , y + 1 , INF, z);
for(int i = 1 ; i <= n + 1 ; i ++ )
{
if(a[i] - a[i - 1] > 0) add_edge(s , i , a[i] - a[i - 1] , 0);
if(a[i] - a[i - 1] < 0) add_edge(i , t , a[i - 1] - a[i] , 0);
}
int ans=0;
//cout<<ans<<endl;
min_cost_max_flow(s, t, ans);
printf("%d\n" , ans);
return 0;
}

未解决的问题

文章目录
  1. 1. bzoj 1061
    1. 1.1. ac code
  2. 2. 未解决的问题
{{ live2d() }}