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
| #include<iostream> #include<cstdio> #include<queue> #include<cstring> #include<algorithm> #define INF 10000000 #define maxn 1510 using namespace std;
int n, m, s, t, _s;
struct node{ int x, y; friend bool operator < (node c, node d){return c.x < d.x;} }a[maxn];
struct Edge{ int to, next, w, fi; }e[2000000]; int sz, head[maxn]; inline void add_edge(int u, int v, int w, int fi){ e[sz].to = v; e[sz].w = w; e[sz].fi = fi; e[sz].next = head[u]; head[u] = sz++; }
inline void Add_edge(int u, int v, int w, int fi){ add_edge(u, v, w, fi); add_edge(v, u, 0, -fi); }
int dis[maxn], fl[maxn], pre[maxn], la[maxn]; bool vis[maxn]; deque<int> Q; bool spfa(){ memset(vis, 0, sizeof vis); memset(dis, 10, sizeof dis); memset(fl, 10, sizeof fl); Q.push_back(s); vis[s] = 1; dis[s] = 0; pre[t] = -1; while(!Q.empty()){ int u = Q.front(); Q.pop_front(); vis[u] = 0; for(int i = head[u]; ~i; i = e[i].next){ int v = e[i].to, w = e[i].w, fi = e[i].fi; if(w > 0 && dis[v] > dis[u] + fi){ dis[v] = dis[u] + fi; fl[v] = min(fl[u], w); la[v] = i; pre[v] = u; if(vis[v]) continue; vis[v] = 1; if(Q.empty() || dis[v] <= dis[Q.front()]) Q.push_front(v); else Q.push_back(v); } } } return pre[t] != -1; } int mc, mf; void McMf(){ while(spfa()){ int now = t; mf += fl[t]; mc += dis[t] * fl[t]; while(now != s){ e[la[now]].w -= fl[t]; e[la[now] ^ 1].w += fl[t]; now = pre[now]; } } cout << -mc; }
int main(){ memset(head, -1, sizeof head); scanf("%d%d", &n, &m); s = 0; t = 2 * n + 2; _s = 2 * n + 1; for(int i = 1; i <= n; ++i) scanf("%d%d", &a[i].x, &a[i].y); sort(a + 1, a + n + 1); for(int i = 1; i <= n; ++i){ Add_edge(_s, i, 1, 0); Add_edge(i, i + n, 1, a[i].x - a[i].y); Add_edge(i + n, t, 1, 0); for(int j = i + 1; j <= n; ++j) if(a[j].x >= a[i].y) Add_edge(i + n, j, 1, 0); } Add_edge(s, _s, m, 0); McMf(); return 0; }
|