P3386 用两个数组能过,用一个标记数组的匈牙利算法为什么会超时?!
查看原帖
P3386 用两个数组能过,用一个标记数组的匈牙利算法为什么会超时?!
234473
_未知楼主2024/12/9 12:05

一个数组

#include <cstdio>
#include <algorithm>

using namespace std;

const int N=1e5+5,M = 1e3+5;
int a[M][M],b[N],n,m,k,vis[M];

bool found (int x) {
	for (int j=1;j<=m;j++) {
		if (a[x][j] == 1 && vis[j] == 0) {
			vis[j] = x;
			return 1;
		}
	}
	for (int j = 1; j <= m; j++) {
		if (a[x][j] == 1 && vis[j] != -1) {
			int t = vis[j];
			vis[j] = -1;
			if (found(t)) {
				vis[j] = x;
				return 1;
			}
			vis[j] = t;
		}
		
	}
	return 0;
} 
int main() {
	scanf ("%d%d%d",&n,&m,&k);
	for (int i=1;i<=k;i++) {
		int x,y;
		scanf ("%d%d",&x,&y) ;
		a[x][y] = 1;
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		if (found(i)) {
			ans++;
		}
	}
	printf ("%d",ans);
	
    return 0;
}

两个数组

#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;

const int N=1e5+5,M = 1e3+5;
int a[M][M],b[N],n,m,k,vis[M],v[M];

bool found (int x) {
	for (int j=1;j<=m;j++) {
		if (a[x][j] == 1 && !v[j]) {
			v[j] = 1;
			if (!vis[j] || found(vis[j])) {
				vis[j] = x;
				return 1;
			}
		}
	}
	return 0;
} 
int main() {
	scanf ("%d%d%d",&n,&m,&k);
	for (int i=1;i<=k;i++) {
		int x,y;
		scanf ("%d%d",&x,&y) ;
		a[x][y] = 1;
	}
	int ans = 0;
	for (int i = 1; i <= n; i++) {
		memset (v, 0, sizeof(v));
		if (found(i)) {
			ans++;
		}
	}
	printf ("%d",ans);
	
    return 0;
}

2024/12/9 12:05
加载中...