传送门
分析
看完之后第一眼反应是个图论问题,想了两种方法,一种是求一个维护联通块个数,一个是网络流建图,后来想想联通块好像不太能写于是往网络流上想
建图比较好建,源点和每一只蜡烛连边,每一只蜡烛和两个点之间连边,流量都为1,费用都为0,剩下的就是费用边应该如何连接的问题了,因为流量和费用并不是一个均衡的关系,所以可以暴力,每个点和汇点之间建50条边,每条边的费用为
k
∗
k
−
(
k
−
1
)
∗
(
k
−
1
)
k * k - (k - 1) * (k - 1)
k∗k−(k−1)∗(k−1),然后跑费用流即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10,M = N * 2;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int h[N],ne[M],e[M],w[M],f[M],idx;
int n,m,S,T;
int q[N],d[N],pre[N],incf[N];
bool st[N];
void add(int a,int b,int c,int d){
ne[idx] = h[a],e[idx] = b,f[idx] = c,w[idx] = d,h[a] = idx++;
ne[idx] = h[b],e[idx] = a,f[idx] = 0,w[idx] = -d,h[b] = idx++;
}
bool spfa(){
int hh = 0,tt = 1;
memset(d,0x3f,sizeof d);
memset(incf,0,sizeof incf);
q[0] = S,d[S] = 0,incf[S] = INF;
while(hh != tt){
int t = q[hh++];
if(hh == N) hh = 0;
st[t] = false;
for(int i = h[t];~i;i = ne[i]){
int ver = e[i];
if(f[i] && d[ver] > d[t] + w[i]){
pre[ver] = i;
d[ver] = d[t] + w[i];
incf[ver] = min(f[i],incf[t]);
if(!st[ver]){
q[tt++] = ver;
if(tt == N) tt = 0;
st[ver] = true;
}
}
}
}
return incf[T] > 0;
}
void EK(int &flow,int &cost){
flow = cost = 0;
while(spfa()){
int t = incf[T];
flow += t,cost += t * d[T];
for(int i = T;i != S;i = e[pre[i] ^ 1]){
f[pre[i]] -= t;
f[pre[i] ^ 1] += t;
}
}
}
int main() {
read(n),read(m);
memset(h,-1,sizeof h);
S = 0,T = N - 10;
for(int i = 1;i <= n;i++) add(S,i,1,0);
for(int i = 1;i <= n;i++){
int x,y;
read(x),read(y);
add(i,x + n,1,0);
add(i,y + n,1,0);
}
for(int i = 1;i <= m;i++)
for(int j = 1;j <= 50;j++)
add(i + n,T,1,j * j - (j - 1) * (j - 1));
int flow,cost;
EK(flow,cost);
printf("%d\n",cost);
return 0;
}