传送门
给出了1e5个点,但是因为最多200条边,也就是最多用到400个点,所用先离散化,然后建图。
建图:
1.对权值为w的区间[u,v],加边id(u)->id(v+1),容量为1,费用为-w;
2.对所有相邻的点加边id(i)->id(i+1),容量为正无穷,费用为0;
3.建立源点汇点,由源点s向最左侧的点加边,容量为K,费用为0,由最右侧的点向汇点加边,容量为K,费用为0
4.跑出最大流后,最小费用取绝对值就是能获得的最大权
#include
#define int long long
using namespace std;
const int maxn = 1e4+10;
const int maxm = 1e5+10;
const int inf = 0x3f3f3f3f;
struct Edge
{
int to,next,cap,flow,cost;
}edge[maxm];
int head[maxn],tol,pre[maxn],dis[maxn];
bool vis[maxn];
void Init(int n)
{
tol = 0;
memset(head,-1, sizeof(head));
}
void add_edge(int u,int v,int cap,int cost)
{
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool Spfa(int s,int t)
{
queueq;
while(!q.empty())
q.pop();
memset(dis,inf, sizeof(dis));
memset(vis,false, sizeof(vis));
memset(pre,-1, sizeof(pre));
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u];i != -1;i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow && dis[v] > dis[u] + edge[i].cost)
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)
return false;
return true;
}
void minCostmaxFlow(int s,int t)
{
int flow = 0,cost = 0;
while(Spfa(s,t))
{
int Min = inf;
for(int i = pre[t];i != -1;i = pre[edge[i^1].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t];i != -1;i = pre[edge[i^1].to])
{
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
printf("%lld\n",-cost);
}
struct node
{
int u,v,flow;
}f[300];
signed main()
{
//freopen("in","r",stdin);
int TT,N,K,M;
scanf("%lld",&TT);
while(TT--)
{
mapmp;
mp.clear();
scanf("%lld%lld%lld",&N,&K,&M);
for(int i = 1;i <= M; i++)
{
scanf("%lld%lld%lld",&f[i].u,&f[i].v,&f[i].flow);
f[i].v += 1;
mp[f[i].u] = 1;
mp[f[i].v] = 1;
}
int cnt = 0;
for(auto it : mp)
{
int id = it.first;
mp[id] = ++cnt;
}
Init(cnt);
int S = 0,T = cnt + 1;
add_edge(S,1,K,0);
add_edge(cnt,T,K,0);
for(int i = 1;i < cnt; i++)
add_edge(i,i + 1,inf,0);
for(int i = 1;i <= M; i++)
add_edge(mp[f[i].u],mp[f[i].v],1,-f[i].flow);
minCostmaxFlow(S,T);
}
return 0;
}