同 poj 3680 https:www.cnblogs.com/lokiii/p/8413139.html
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
const int N=1000005,inf=1e9;
int n,m,k,a[1005],tot,h[N],cnt=1,dis[N],s,t,ans,fr[N];
bool v[N];
map<int,int>mp;
struct qwe
{
int ne,no,to,va,c;
}e[N<<2];
struct qw
{
int l,r,w;
}b[1005];
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
void add(int u,int v,int w,int c)
{
cnt++;
e[cnt].ne=h[u];
e[cnt].no=u;
e[cnt].to=v;
e[cnt].va=w;
e[cnt].c=c;
h[u]=cnt;
}
void ins(int u,int v,int w,int c)
{
add(u,v,w,c);
add(v,u,0,-c);
}
bool spfa()
{
queue<int>q;
for(int i=s;i<=t;i++)
dis[i]=-inf;
dis[s]=0;
v[s]=1;
q.push(s);
while(!q.empty())
{
int u=q.front();
q.pop();
v[u]=0;
for(int i=h[u];i;i=e[i].ne)
if(e[i].va>0&&dis[e[i].to]<dis[u]+e[i].c)
{
dis[e[i].to]=dis[u]+e[i].c;
fr[e[i].to]=i;
if(!v[e[i].to])
{
v[e[i].to]=1;
q.push(e[i].to);
}
}
}
return dis[t]!=-inf;
}
void mcf()
{
int x=inf;
for(int i=fr[t];i;i=fr[e[i].no])
x=min(x,e[i].va);
for(int i=fr[t];i;i=fr[e[i].no])
{
e[i].va-=x;
e[i^1].va+=x;
ans+=x*e[i].c;
}
}
int main()
{
n=read(),k=read();
for(int i=1;i<=n;i++)
{
b[i].l=read(),b[i].r=read();
if(b[i].l>b[i].r)
swap(b[i].l,b[i].r);
b[i].w=b[i].r-b[i].l;
a[++tot]=b[i].l,a[++tot]=b[i].r;
}
sort(a+1,a+1+tot);
m=unique(a+1,a+1+tot)-a-1;
for(int i=1;i<=m;i++)
mp[a[i]]=i;
for(int i=1;i<=n;i++)
ins(mp[b[i].l],mp[b[i].r],1,b[i].w);
s=0,t=m+1;
for(int i=0;i<=m;i++)
ins(i,i+1,k,0);
while(spfa())
mcf();
printf("%d
",ans);
return 0;
}