题意:n只蜡烛,m个区域,第i个蜡烛可以放在第或者
区域里,每个区域所耗时间等于占用该区域蜡烛个数的平方。求总的最小消耗时间。
思路:可以看成每个蜡烛可以流向两个区域,建立两个容量为1,费用为0的边,建一个源点与n个蜡烛连边,容量为1,费用为0,再建一个汇点让m个区域与之连边,容量为每个区域对应的入度x,费用为,那么我们可以把这一条边拆成x条边,第i条边容量为1,费用为2*i-1。这样由于求最小费用,所以当流量为f时,经过的边即为第1条到第f条边,总费用=f*f,然后跑一遍最小费用最大流就行了。
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define ll long long
#define PI acos(-1)
#define INF 0x3f3f3f3f
#define NUM 50010
#define debug true
#define lowbit(x) ((-x)&x)
#define ffor(i,d,u) for(int i=d;i<=u;++i)
#define _ffor(i,u,d) for(int i=u;i>=d;--i)
#define mst(array,Num) memset(array,Num,sizeof(array))
const int p = 1e9+7;
int n,m,ednum;
int head[105],h[105]={};
int pre[105],dist[105];
int a[51],b[51],ss[51]={};
struct edge
{
int next,to,f,c;
}e[8010];
struct Vertex
{
int id,dis;
bool operator>(const Vertex &x)const
{
return dis > x.dis ;
}
};
template <typename T>
inline void read(T &x){
char ch = getchar();x = 0;
for (; ch < '0' || ch > '9'; ch = getchar());
for (; ch >='0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
}
template <typename T>
inline void write(T x)
{
int len=0;char c[21];
if(x<0)putchar('-'),x*=(-1);
do{++len;c[len]=(x%10)+'0';}while(x/=10);
_ffor(i,len,1)putchar(c[i]);
}
inline void addedge(const int &x,const int &y,const int &flow,const int &cost)
{
e[++ednum].to = y,e[ednum].f = flow,e[ednum].next = head[x],head[x] = ednum,e[ednum].c = cost;
e[++ednum].to = x,e[ednum].f = 0,e[ednum].next = head[y],head[y] = ednum,e[ednum].c = -cost;
}
inline bool Dij(const int &s,const int &t)
{
Vertex x,y;
priority_queue < Vertex , vector < Vertex > , greater < Vertex > > q;
mst(dist,INF);
x.id = s,dist[s] = x.dis = 0;
pre[s] = -1;
q.push(x);
while(!q.empty())
{
x = q.top(),q.pop();
if(x.dis > dist[x.id])continue;
for(int i = head[x.id] ; i != -1 ; i = e[i].next)
{
y.id = e[i].to;
if(e[i].f > 0 && dist[y.id] > dist[x.id]+e[i].c+h[x.id]-h[y.id])
{
y.dis = dist[y.id] = dist[x.id]+e[i].c+h[x.id]-h[y.id];
pre[y.id] = i;
q.push(y);
}
}
}
if(dist[t] == INF)return false;
return true;
}
inline void MinCost_MaxFlow(const int &s,const int &t,int &cost,int &maxflow)
{
int d=INF;
while(d > 0&&Dij(s,t))
{
ffor(i,0,t) h[i] += dist[i];
d = INF;
for(int i = pre[t] ; i != -1 ; i = pre[e[i^1].to])
d = min(d , e[i].f);
maxflow += d , cost += h[t] * d;
for(int i = pre[t] ; i != -1 ; i = pre[e[i^1].to])
{
e[i].f -= d;
e[i^1].f += d;
}
}
}
inline void AC()
{
int x,y,s,t;
int cost,maxflow=0;
read(n),read(m);
s=0,t=n+m+1;
maxflow = 0,ednum = -1,mst(head,-1);
ffor(i,1,n)
{
read(a[i]),read(b[i]);
addedge(0,i,1,0);
addedge(i,a[i]+n,1,0);
addedge(i,b[i]+n,1,0);
++ss[a[i]],++ss[b[i]];
}
ffor(i,1,m)
{
cost = 1;
ffor(j,1,ss[i])
{
addedge(i+n,t,1,cost);
cost += 2;
}
}
cost = 0;
MinCost_MaxFlow(s,t,cost,maxflow);
write(cost),puts("");
}
int main()
{
AC();
return 0;
}