18分求调
查看原帖
18分求调
999274
CNS_5t0_0r2楼主2025/1/21 14:28
#include<bits/stdc++.h>
using namespace std;
const int N = 59,M = (N * N << 2) + 9;
int n,k,s,t;
int ans;
struct edge{
	int to,cap,nex;
} e[M << 1];
int head[N << 1],ecnt = 1;
int head2[N << 1];//分层图的表头 
void addedge(int u,int v,int c){
	ecnt++;
	e[ecnt] = (edge){v,c,head[u]};
	head[u] = ecnt;
}
queue<int> q;
int dep[N << 1];//层次 
bool bfs(){//构造分层图 
	memset(dep,0,sizeof dep);
	q.push(s);
	dep[s] = 1;
	head2[s] = head[s];
	while(!q.empty()){
		int u = q.front();
		q.pop();
		for(int i = head[u];i;i = e[i].nex){
			int v = e[i].to,c = e[i].cap;
			if(dep[v] || !c)
				continue;
			head2[v] = head[v];
			dep[v] = dep[u] + 1;
			q.push(v);
		}
	}
	return dep[t];
}
int dfs(int u,int flow){//在分层图上增广 
	if(u == t)
		return flow;
	int rest = flow,tmp;
	for(int i = head2[u];i && rest;i = e[i].nex){
		head2[u] = i;
		int v = e[i].to,c = e[i].cap;
		if(dep[v] != dep[u] + 1 || !c)
			continue;
		tmp = dfs(v,min(rest,c));
		if(!tmp)
			dep[v] = 0;//当无法从v 增广时,将v从分层图中删除
		e[i].cap -= tmp;
		e[i ^ 1].cap += tmp;
		rest -= tmp;
	}
	return flow - rest;//流到u的流量减去流出u后剩余的流量就是流到汇点的流量
}
signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);cout.tie(0);
	cin >> n >> k;
	s = 0;t = n + n + 1;
	for(int i = 1;i <= n;i++){
		char s[N];
		cin >> (s + 1);
		for(int j = 1;j <= n;j++){
			if(s[j] == 'Y')
				ans++;
			else{
				addedge(i,j + n,1);
				addedge(j + n,i,0);
			}
		}
	}
	if(ans >= n){
		cout << n;
		return 0;
	}
	for(int i = 1;i <= n;i++){
		addedge(s,i,k);
		addedge(i,s,0);
	}
	for(int i = n + 1;i <= n + n;i++){
		addedge(i,t,k);
		addedge(t,i,0);
	}
	int flow = 0;
	while(bfs())
		while(flow = dfs(s,n - ans))
			ans += flow;
	cout << ans;
	return 0;
}
2025/1/21 14:28
加载中...