您的位置:首页 > 大数据 > 人工智能

uva12092 Paint the Roads

2017-02-24 18:22 399 查看
In a country there are n cities connected by m one way roads. You can

paint any of these roads. To paint a road it costs d unit of money

where d is the length of that road. Your task is to paint some of the

roads so that the painted roads can be partitioned into some dis-

joint cycles such that every vertex appears in exactly k of these

disjoint cycles. But you have to minimize the costs of painting these

roads. Input First line of the input con- tains T the number of test

case. Then following lines contains T Test cases. Each case starts

with a line containing 3 integers n (1  n  40), m (1  m  2000) and

k (1  k and 1  k  n  100). Next m lines contain description of m

roads. Each line contains three integers f , t (0  f;t< n and f ̸

= t ) and d (0  d< 100). That means there is a road of d length from city f to city t . You can assume that there will be at most one road

in one direction between two cities. Output For each test case output

contains 1 integer denoting the minimum unit of money needed to paint

roads. In the case it is impossible to paint the roads maintaining the

constraints output `

-1 ‘.

每个点处在k个环的充分必要条件是每个点的入度和出度都为k。必要性很好说明,充分性可以不断找到环并且删除。

这样拆点限流跑费用流即可。

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int s=105,t=106,mod=107,oo=0x3f3f3f3f;
int fir[110],ne[20010],to[20010],w[20010],c[20010],
que[110],in[110],minw[110],len[110],fa[110],
n,m,k,num;
void add(int u,int v,int x,int y)
{
num++;
ne[num*2]=fir[u];
fir[u]=num*2;
to[num*2]=v;
w[num*2]=x;
c[num*2]=y;
ne[num*2+1]=fir[v];
fir[v]=num*2+1;
to[num*2+1]=u;
w[num*2+1]=0;
c[num*2+1]=-y;
}
void init()
{
int u,v,x;
num=0;
memset(fir,0,sizeof(fir));
scanf("%d%d%d",&n,&m,&k);
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&x);
add(u,v+n,1,x);
}
for (int i=0;i<n;i++)
{
add(s,i,k,0);
add(i+n,t,k,0);
}
}
void solve()
{
int u,v,hd,tl,ans=0;
while (1)
{
hd=0,tl=1;
in[s]=1;
que[0]=s;
memset(len,0x3f,sizeof(len));
len[s]=0;
memset(minw,0,sizeof(minw));
minw[s]=oo;
while (hd!=tl)
{
u=que[hd++];
hd%=mod;
for (int i=fir[u];i;i=ne[i])
if (w[i]&&len[v=to[i]]>len[u]+c[i])
{
len[v]=len[u]+c[i];
minw[v]=min(minw[u],w[i]);
fa[v]=i;
if (!in[v])
{
que[tl++]=v;
tl%=mod;
in[v]=1;
}
}
in[u]=0;
}
if (!minw[t]) break;
ans+=minw[t]*len[t];
for (int i=fa[t];i;i=fa[to[i^1]])
{
w[i]-=minw[t];
w[i^1]+=minw[t];
}
}
for (int i=fir[s];i;i=ne[i])
if (w[i])
{
printf("-1\n");
return;
}
printf("%d\n",ans);
}
int main()
{
int T;
scanf("%d",&T);
while (T--)
{
init();
solve();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  费用流