Tour (KM algorithm + negation)

In the kingdom of Henryy, there are N (2 <= N <= 200) cities, with M (M <= 30000) one-way roads connecting them. You are lucky enough to have a chance to have a tour in the kingdom. The route should be designed as: The route should contain one or more loops. (A loop is a route like: A->B->……->P->A.)
Every city should be just in one route.
A loop should have at least two cities. In one route, each city should be visited just once. (The only exception is that the first and the last city should be the same and this city is visited twice.)
The total distance the N roads you have chosen should be minimized.

Input An integer T in the first line indicates the number of the test cases.
In each test case, the first line contains two integers N and M, indicating the number of the cities and the one-way roads. Then M lines followed, each line has three integers U, V and W (0 < W <= 10000), indicating that there is a road from U to V, with the distance of W.
It is guaranteed that at least one valid arrangement of the tour is existed.
A blank line is followed after each test case. Output For each test case, output a line with exactly one integer, which is the minimum total distance. Sample Input
1
6 9
1 2 5
2 3 5
3 1 10
3 4 12
4 1 8
4 6 11
5 4 7
5 6 9
6 5 4
Sample Output
42

The meaning of the title: Given a directed graph, design one or more loops to cover all points, and find the minimum weight

Idea: The network flow problem seeks the maximum weight, and only needs to be negated when the edge relationship is stored

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#define Inf 0x3f3f3f3f
using namespace std;
const int N = 205;
int vx [N], vy [N];
int dx[N],dy[N];
int match[N],slack[N];
int G[N][N],n,m;
int Find (int u) {
	vx[u]=1;
	for(int i=1;i<=n;i++){
		if(vy[i]) continue;
		int gap=dx[u]+dy[i]-G[u][i];
		if(gap==0){
			vy[i]=1;
			if(match[i]==-1||Find(match[i])){
				match[i]=u;
				return 1;
			}
		}
		else slack[i]=min(slack[i],gap);
	}
	return 0;
}
void KM(){
	memset(dx,-Inf,sizeof(dx));
	memset(dy,0,sizeof(dy));
	memset(match,-1,sizeof(match));
	for(int i=1;i<=n;i++)
	for(int j=1;j<=n;j++)
	   dx[i]=max(dx[i],G[i][j]);
	for(int i=1;i<=n;i++){
		memset(slack,Inf,sizeof(match));
		while(1){
			memset(vx,0,sizeof(vx));
			memset(vy,0,sizeof(vy));
			if(Find(i))  break;	
			
			int dis=Inf;
			
			for(int j=1;j<=n;j++){
				if(!vy[j]) dis=min(dis,slack[j]);
			}
			
			for(int j=1;j<=n;j++){
				if(vx[j]) dx[j]-=dis;
				if(vy[j]) dy[j]+=dis;
				else slack[j]-=dis;
			}
		}
	}
	int ans=0;
	for(int i=1;i<=n;i++)
	  if(match[i]!=-1) ans+=G[match[i]][i];
	printf("%d\n",-ans);
}
int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		memset(G,-Inf,sizeof(G));
		scanf("%d%d",&n,&m);
		for(int i=0;i<m;i++){
			int x,y,w;
			scanf("%d%d%d",&x,&y,&w);
			G[x][y]=max(G[x][y],-w);
		}

		KM();
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324882711&siteId=291194637