题目链接:UVALive-2197
题意:n个点,m条边,还有一个k,给出每条边的信息,让你选择一些边,使得这些边组成的图里面,每个点只属于k个回路上,问最小的费用
如果每个点都只在k个回路上,那么这些点的出度入度是相等的,都是等于k,所以对于每个点,拆点分别连源点汇点,容量为k,费用为0,然后边就正常的连上,容量为1,费用为边权,跑一遍费用流,若最后的流量等于k*n,就是答案,否则就是-1
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=110;
const int maxm=1e5+7;
const int inf=0x3f3f3f3f;
struct Node
{
int to;
int capa;
int cost;
int next;
}edge[maxm];
int cnt;
int source,sink;
int n,m,k;
int head[maxn];
int dis[maxn];
int rec[maxn];
int pre[maxn];
bool vis[maxn];
void init()
{
cnt=0;
memset(head,-1,sizeof(head));
return;
}
void add(int u,int v,int capa,int cost)
{
edge[cnt].to=v;
edge[cnt].capa=capa;
edge[cnt].cost=cost;
edge[cnt].next=head[u];
head[u]=cnt++;
edge[cnt].to=u;
edge[cnt].capa=0;
edge[cnt].cost=-cost;
edge[cnt].next=head[v];
head[v]=cnt++;
return;
}
bool spfa()
{
memset(dis,inf,sizeof(dis));
memset(pre,-1,sizeof(pre));
memset(rec,-1,sizeof(rec));
memset(vis,false,sizeof(vis));
queue<int> que;
que.push(source);
dis[source]=0;
vis[source]=true;
while(!que.empty())
{
int node=que.front();
que.pop();
vis[node]=false;
for(int i=head[node];~i;i=edge[i].next)
{
int v=edge[i].to;
if(edge[i].capa>0&&dis[v]>dis[node]+edge[i].cost)
{
dis[v]=dis[node]+edge[i].cost;
rec[v]=i;
pre[v]=node;
if(!vis[v])
{
vis[v]=true;
que.push(v);
}
}
}
}
return dis[sink]!=inf;
}
int mcmf()
{
int maxflow=0;
int mincost=0;
while(spfa())
{
int node=sink;
int minn=inf;
while(node!=source)
{
minn=min(edge[rec[node]].capa,minn);
node=pre[node];
}
maxflow+=minn;
node=sink;
while(node!=source)
{
mincost+=minn*edge[rec[node]].cost;
edge[rec[node]].capa-=minn;
edge[rec[node]^1].capa+=minn;
node=pre[node];
}
}
if(maxflow==k*n) return mincost;
return -1;
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int test;
scanf("%d",&test);
while(test--)
{
init();
scanf("%d%d%d",&n,&m,&k);
source=0;
sink=n*2+1;
for(int i=1;i<=n;i++)
{
add(source,i,k,0);
add(i+n,sink,k,0);
}
for(int i=0;i<m;i++)
{
int u,v,w;
scanf("%d%d%d",&u,&v,&w);
add(u+1,v+n+1,1,w);
}
printf("%d\n",mcmf());
}
return 0;
}