链接:https://www.nowcoder.com/acm/contest/206/A
来源:牛客网
恬恬的生日临近了。宇扬给她准备了一个蛋糕。
正如往常一样,宇扬在蛋糕上插了n支蜡烛,并把蛋糕分为m个区域。因为某种原因,他必须把第i根蜡烛插在第ai个区域或第bi个区域。区域之间是不相交的。宇扬在一个区域内同时摆放x支蜡烛就要花费x2的时间。宇扬布置蛋糕所用的总时间是他在每个区域花的时间的和。
宇扬想快些见到恬恬,你能告诉他布置蛋糕最少需要多少时间吗?输入描述:
第一行包含两个整数n,m(1 ≤ n ≤ 50, 2≤ m≤ 50)。 接下来n行,每行两个整数ai,bi(1 ≤ ai, bi ≤ m)。输出描述:
一个整数表示答案。示例1
输入
3 3 1 2 1 2 1 2输出
5示例2
输入
3 3 1 2 2 3 1 3输出
3一道经典的拆点费用流。
左边n个点代表n个蜡烛,右边m*n个点代表m个part,每个part被拆成n个点。源点向每个左边的点连一个费用为0,流量为1的边。每个右边的点向汇点连一条费用为0,流量为1的边。每个蛋糕向可以放的两个part的所有点连边,连向第i个点的费用是i^2-(i-1)^2,流量为1.
扫描二维码关注公众号,回复: 3491400 查看本文章#include <stdio.h> #include <algorithm> #include <string.h> #include <iostream> #include <string> #include <queue> using namespace std; const int MAXN = 10000; const int MAXM = 100000; const int inf = 0x3f3f3f3f; struct Edge { int to, next, cap, flow, cost; //cap是最大容量 flow是流量 }edge[MAXM]; int head[MAXN], tol; int pre[MAXN], dis[MAXN]; bool vis[MAXN]; int m, n, cost;//节点总个数,节点编号从0~N-1 void addedge(int u, int v, int cap, int cost) { edge[tol].to = v; edge[tol].cap = cap; edge[tol].cost = cost; edge[tol].flow = 0; edge[tol].next = head[u]; head[u] = tol++; edge[tol].to = u; edge[tol].cap = 0; edge[tol].cost = -cost; edge[tol].flow = 0; edge[tol].next = head[v]; head[v] = tol++; } bool spfa(int s, int t) { queue<int>q; q.push(s); for (int i = 0; i < n+m+2; i++) { dis[i] = inf; pre[i] = -1; vis[i] = false; } dis[s] = 0; vis[s] = true; while (!q.empty()) { int u = q.front(); q.pop(); vis[u] = false; for (int i = head[u]; i != -1; i = edge[i].next) { int v = edge[i].to; 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]) { vis[v] = true; q.push(v); } } } } if (pre[t] == -1) { return false; } else return true; } //返回的是最大流,cost存的是最小费用 int mincost(int s, int t, int &cost) { int flow = 0; cost = 0; while (spfa(s, t)) { int _min = inf; for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]) { if (_min > edge[i].cap - edge[i].flow) { _min = edge[i].cap - edge[i].flow; } } for (int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]) { edge[i].flow += _min; edge[i ^ 1].flow -= _min; cost += edge[i].cost * _min; } flow += _min; } return flow; } int main() { //freopen("C:/input.txt", "r", stdin); scanf("%d%d", &n, &m); int s = 0, t = n + m + 1; tol = 0; memset(head, -1, sizeof(head)); for (int i = 1; i <= n; i++) { int a, b; scanf("%d%d", &a, &b); addedge(s, i, 1, 0); addedge(i, a + n, 1, 0); addedge(i, b + n, 1, 0); } for (int i = 1; i <= m; i++) { for (int j = 1; j <= 99; j+=2) //2*50-1 { addedge(i + n, t, 1, j); } } mincost(0, n + m + 1, cost); printf("%d\n", cost); return 0; }
牛客国庆集训派对Day6 A Birthday (拆点费用流)
猜你喜欢
转载自blog.csdn.net/Evildoer_llc/article/details/82958511
今日推荐
周排行