这题最开始再网络赛的时候遇到,第一想法是贪心或者dp,然后发现需要记录的转态太多了。一看区间个数又很想网络流,所以就yy出了一个假算法,太丑了就不说了。
这题正确的思路是
将答案拆分成k条路径,每条路径满足包含的区间之间互相没有交集。如果将这k条路径按照包含区间的个数排序,那么满足的关系就是下一个路径包含的区间一定被上一个路径的区间所包含。问题转化为k条路径的最大费用。
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef int lint;
const int inf = 0x3f3f3f3f;
const lint maxn = 10000;
const lint maxm = 20000000;
struct mcmf{
int he[maxn],tot,edge[maxm],ne[maxm],ver[maxm],cost[maxm];
int pre[maxn],d[maxn];
bool vis[maxn];
int n;
void init(int x){
n = x;
tot = 1;
for( int i = 0;i <= n;i++ ) he[i] = 0;
}
void add(int x,int y,int cap,int c){
ver[++tot] = y;
ne[tot] = he[x];
he[x] = tot;
edge[tot] = cap;
cost[tot] = c;
ver[++tot] = x;
ne[tot] = he[y];
he[y] = tot;
edge[tot] = 0;
cost[tot] = -c;
}
bool spfa(int s,int t){
queue<int>q;
for(int i = 0;i < n;i++){
d[i] = inf;
vis[i] = false;
pre[i] = -1;
}
d[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty()){
int x = q.front();
q.pop();
vis[x] = false;
for(int cure = he[x]; cure ;cure = ne[cure]){
int y = ver[cure];
if(edge[cure] && d[y] > d[x] + cost[cure] ){
d[y] = d[x] + cost[cure];
pre[y] = cure;
if(!vis[y]){
vis[y] = true;
q.push(y);
}
}
}
}
if(pre[t] == -1)return false;
else return true;
}
int mincost(int s,int t,int &cc){
int flow = 0;
lint prec = 0;
cc = 0;
while(spfa(s,t)){
int mn = inf;
for(int cure = pre[t];cure != -1;cure = pre[ ver[cure^1] ]){
if(mn > edge[cure])
mn = edge[cure];
}
for(int cure = pre[t];cure != -1;cure = pre[ ver[cure^1] ]){
edge[cure] -= mn;
edge[cure^1] += mn;
cc += cost[cure] * mn;
}
if( cc > prec ){
cc = prec;
break;
}
prec = cc;
flow += mn;
}
return flow;
}
} g;
lint a[maxn],b[maxn];
vector<lint> ve;
void discrete(){
sort( ve.begin(),ve.end() );
ve.erase( unique( ve.begin(),ve.end() ),ve.end() );
}
lint H( lint x ){
return lower_bound( ve.begin(),ve.end(),x ) - ve.begin() + 1;
}
lint isstart[maxn];
void init(){
ve.clear();
memset(isstart,0,sizeof( isstart ));
}
int main(){
lint T,n,k;
scanf("%d%d",&n,&k);
init();g.init( 2*n+10 );
for( lint i = 1;i<= n;i++ ){
scanf("%d%d",&a[i],&b[i]);
if( a[i] > b[i] ) swap( a[i],b[i] );
ve.push_back(a[i]);ve.push_back(b[i]);
}
discrete();
for( lint i = 1;i <= n;i++ ){
lint l = H(a[i]);
isstart[ l ] = 1;
}
for( lint i = 1;i <= n;i++ ){
lint l = H(a[i]);
lint r = H(b[i]);
g.add( l,r,1,a[i]-b[i] );
}
for( lint i = 1;i < ve.size();i++ ){
g.add( i,i+1,inf,0 );
}
LL ss = 0,tt = ve.size()+1;
g.add( ss,1,k,0 );g.add( ve.size(),tt,k,0 );
lint ans = 0;
g.mincost(ss,tt,ans );
cout << -ans << endl;
return 0;
}