题目描述:
题目入口
恬恬的生日临近了。宇扬给她准备了一个大蛋糕。
正如往常一样,宇扬在蛋糕上插了n支蜡烛,并把蛋糕分为m个区域。因为某种原因,他必须把第i根蜡烛插在第ai个区域或第bi个区域。区域之间是不相交的。宇扬在一个区域内同时摆放x支蜡烛就要花费x2的时间。宇扬布置蛋糕所用的总时间是他在每个区域花的时间的和。
宇扬想快些见到恬恬,你能告诉他布置蛋糕最少需要多少时间吗?
输入:
第一行包含两个整数n,m(1 ≤ n ≤ 50, 2 ≤ m ≤ 50)。
接下来n行,每行两个整数ai, bi(1 ≤ ai, bi ≤ m)。
输出:
一个整数表示答案。
样例输入
3 3
1 2
1 2
1 2
样例输出
5
建图跑 最小费用最大流
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100 + 100;
const int maxm = 100 + 100;
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int,int> P;
//const LL mod = 1e9 + 7;
#define PI 3.1415926
#define sc(x) scanf("%d",&x)
#define pf(x) printf("%d",x)
#define pfn(x) printf("%d\n",x)
#define pfln(x) printf("%lld\n",x)
#define pfs(x) printf("%d ",x)
#define rep(n) for(int i = 0; i < n; i++)
#define per(n) for(int i = n-1; i >= 0; i--)
#define mem(a,x) memset(a,x,sizeof(a))
struct edge
{
int from,to,cap,flow,cost;
edge(int from,int to, int cap, int flow, int cost) : from(from),to(to),cap(cap),flow(flow),cost(cost) {}
};
int n,m,s,t;
int tot = 0;
vector<edge> E;
vector<int> G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void addedge(int from, int to, int cap, int cost)
{
E.push_back(edge(from,to,cap,0,cost));
E.push_back(edge(to,from,0,0,-cost));
tot = E.size();
G[from].push_back(tot-2);
G[to].push_back(tot-1);
}
bool BellmanFord(int s, int t, int &flow, int &cost)
{
rep(n) d[i] = INF;
mem(inq,0);
d[s] = 0,inq[s] = 1; p[s] = 0, a[s] = INF;
queue<int> Q;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();Q.pop();
inq[u] = 0;
for(int i = 0; i < G[u].size(); i++)
{
edge e = E[G[u][i]];
if(e.cap > e.flow && d[e.to] > d[u] + e.cost)
{
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u],e.cap - e.flow);
if(!inq[e.to]) {Q.push(e.to); inq[e.to] = 1;}
}
}
}
if(d[t] == INF) return false;
flow += a[t];
cost += d[t] * a[t];
int u = t;
while(u != s)
{
E[p[u]].flow += a[t];
E[p[u]^1].flow -= a[t];
u = E[p[u]].from;
}
return true;
}
int mincost(int s, int t)
{
int flow = 0,cost = 0;
//cout << "***" << endl;
while(BellmanFord(s,t,flow,cost)) ;
//cout<<cost << endl;
return cost;
}
int main()
{
s = 0,t = 150;
int N,M;
sc(N),sc(M);
for(int i = 1;i <= N; i++)
addedge(s,i,1,0);
for(int i = 1; i <= M; i++)
for(int j = 1; j <= 60; j++)
addedge(i+50,t,1,2*j-1);
n = 200;
for(int i = 1; i <= N; i++)
{
int x1,x2;
sc(x1),sc(x2);
addedge(i,x1+50,1,0);
addedge(i,x2+50,1,0);
}
pfn(mincost(s,t));
return 0;
}