Cyclic Tour
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/65535 K (Java/Others)Total Submission(s): 861 Accepted Submission(s): 438
The first line of each test case contains two integers N (N ≤ 100) and M, indicating the number of cities and the number of roads. The M lines followed, each of them contains three numbers A, B, and C, indicating that there is a road from city A to city B, whose length is C. (1 ≤ A,B ≤ N, A ≠ B, 1 ≤ C ≤ 1000).
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define INF 9999999
#define maxn 205
int lx[maxn],ly[maxn];
int w[maxn][maxn];
int Match[maxn],visx[maxn],visy[maxn];
int slack[maxn];
int ans,n,m;
bool findPath(int x)
{
int tmp;
visx[x]=1;
for(int y=1; y<=n; y++)
{
if(visy[y])continue;
if(w[x][y]==lx[x]+ly[y])
{
visy[y]=1;
if(!Match[y]||findPath(Match[y]))
{
Match[y]=x;
return true;
}
}
else
slack[y]=min(slack[y],w[x][y]-lx[x]-ly[y]);
}
return false;
}
void km()
{
memset(Match,0,sizeof(Match));
memset(ly,0,sizeof(ly));
for(int i=1; i<=n; i++)
{
lx[i]=INF;
for(int j=1; j<=n; j++)
lx[i]=min(lx[i],w[i][j]);
}
for(int x=1; x<=n; x++)
{
for(int i=1; i<=n; i++)
slack[i]=INF;
while(true)
{
memset(visx,0,sizeof(visx));
memset(visy,0,sizeof(visy));
if(findPath(x))break;
int tmp=INF;
for(int i=1; i<=n; i++)
{
if(!visy[i])
{
if(tmp>slack[i])
tmp=slack[i];
}
}
if(tmp==INF)return ;
for(int i=1; i<=n; i++)
{
if(visx[i])lx[i]+=tmp;
if(visy[i])ly[i]-=tmp;
}
}
}
}
int main()
{
int cas;
while(scanf("%d %d",&n,&m)!=EOF)
{
int a,b,c;
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
{
w[i][j]=INF;
}
for(int i=0; i<m; i++)
{
cin>>a>>b>>c;
if(w[a][b]>c)
w[a][b]=c;
}
km();
int ans=0;
int flag=0;
for(int i=1; i<=n; i++)
{
if(Match[i]==0||w[Match[i]][i]==INF)
{
flag=1;
cout<<"-1"<<endl;
break;
}
if(Match[i])
ans+=w[Match[i]][i];
}
if(!flag)
cout<<ans<<endl;
}
return 0;
}