显示代码纯文本
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<deque>
#include<iostream>
using namespace std;
const int SIZEN=1000,SIZEM=30010,INF=0x7fffffff/2;
int N,M,C,S,T,tot=0;
int ans=0;
deque<int> s[SIZEN];
int f[SIZEN],key[SIZEN];
class miku
{
public:
int fr,to,cost,cap,flow;
miku(){}
miku(int a,int b,int c,int d,int e)
{
fr=a,to=b,cap=c,flow=d,cost=e;
}
}E[6*SIZEM];
void add(int fr,int to,int cap,int cost)
{
s[fr].push_back(tot);
E[tot++]=miku(fr,to,cap,0,cost);
s[to].push_back(tot);
E[tot++]=miku(to,fr,0,0,-cost);
}
void read()
{
scanf("%d%d%d",&N,&M,&C);
S=0,T=3*N+1;
int fr,to,cost;
for(int i=1;i<=M;i++)
{
scanf("%d%d%d",&fr,&to,&cost);
add(fr,to+N,1,cost);
}
for(int i=1;i<=N;i++)
{
add(S,i,1,0),add(i+N,T,1,0);
add(S,i+2*N,1,0),add(i+2*N,i+N,1,C);
}
}
bool SPFA()
{
for(int i=1;i<=T;i++)
{
f[i]=INF;
key[i]=-1;
}
deque<int> Q;
Q.push_back(0);
bool inq[SIZEN]={0};
inq[0]=1;
while(!Q.empty())
{
int x=Q.front();Q.pop_front();inq[x]=0;
for(int i=0;i<s[x].size();i++)
{
miku &v=E[s[x][i]];
if(v.cap<=v.flow) continue;
if(f[v.to]>f[x]+v.cost)
{
f[v.to]=f[x]+v.cost;
key[v.to]=s[x][i];
if(!inq[v.to])
{
Q.push_back(v.to);
inq[v.to]=1;
}
}
}
}
if(f[T]==INF) return 0;
return 1;
}
void dfs()
{
int x=T;
//cout<<f[T]<<endl;
ans+=f[T];
while(x!=0)
{
int tem=key[x];
E[tem].flow+=1;
E[tem^1].flow-=1;
x=E[tem].fr;
}
}
void work()
{
while(SPFA()) dfs();
printf("%d",ans);
}
int main()
{
freopen("asm_lis.in","r",stdin);
freopen("asm_lis.out","w",stdout);
read();
work();
return 0;
}