网络流写法,对树进行二分染色,照着最小点权覆盖集的方式建图,跑一遍dinic即可
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5, M = 4e4 + 5;
#define int long long
#define double long double
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
int e[M], f[M], ne[M], idx, h[M], du[M], rh[M], S = M - 2, T = M - 1, cur[M], d[M];
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
void add1(int a, int b, int c, int d) {
e[idx] = b, f[idx] = c, ne[idx] = rh[a], rh[a] = idx++;
e[idx] = a, f[idx] = d, ne[idx] = rh[b], rh[b] = idx++;
}
void build(int u, bool flag) {
if (!flag)
add1(S, u, 1, 0);
else
add1(u, T, 1, 0);
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
if (!flag)
add1(u, j, 1e9, 0);
else
add1(j, u, 1e9, 0);
build(j, 1 - flag);
}
}
bool bfs(){
memset(d,0x3f,sizeof d);
d[S]=0;
cur[S]=rh[S];
queue<int>q;
q.push(S);
while(q.size()){
int t=q.front();
q.pop();
for(int i=rh[t];~i;i=ne[i]){
int j=e[i];
if(f[i]&&d[j]>d[t]+1){
d[j]=d[t]+1;
cur[j]=rh[j];
if(j==T) return 1;
q.push(j);
}
}
}
return 0;
}
int dfs(int u,int limit){
if(u==T) return limit;
int flow=0;
for(int i=cur[u];~i&&limit>flow;i=ne[i]){
int j=e[i];
cur[u]=i;
if(f[i]&&d[j]==d[u]+1){
int t=dfs(j,min(f[i],limit-flow));
if(!t) d[j]=0x3f3f3f3f;
flow+=t,f[i]-=t,f[i^1]+=t;
}
}
return flow;
}
int dinic(){
int r=0,flow;
while(bfs()) while(flow=dfs(S,1e9)) r+=flow;
return r;
}
void solve() {
int n;
while (~scanf("%lld", &n)) {
idx = 0;
memset(rh, -1, sizeof rh);
memset(h, -1, sizeof h);
memset(du, 0, sizeof du);
for (int i = 0; i < n; i++) {
int now, k;
scanf("%lld:(%lld)", &now, &k);
while (k--) {
int t;
scanf("%lld", &t);
add(now, t);
du[t]++;
}
}
int root;
if(idx&1) idx++;
for (int i = 0; i < n; i++)
if (!du[i]) {
root = i;
break;
}
build(root, 0);
cout << dinic() << endl;
}
}
signed main() {
solve();
return 0;
}
orz
我去,学长tql
我是菜🐔
牛!
完全没有必要的做法,浪费了很好的性质,当时不懂事瞎写的
哈哈哈,能写出来了已经很厉害了,大佬加油加油