https://codeforces.com/group/NVaJtLaLjS/contest/255106/problem/M
题意:DAG最大独立集
思路:一开始一直想DAG最大独立集=补图最大团,然后blabla…
实际上又是用到了Dilworth定理!
偏序集的最大反链
定义:偏序集中的最大独立集。
Dilworth定理:对于任意偏序集都有,最大反链(最大独立集)=最小链的划分(最小可相交路径覆盖).
通过Dilworth定理, 我们就可以把偏序集的最大独立集问题转化为最小可相交路径覆盖问题了。
之前早期做过的那道《拦截导弹》也用到了这个定理:将序列划分若干个为不上升子序列,使得划分的个数最小(最小 链的划分),那么这个个数等于序列的最长上升子序列的大小(最大反链)。
发现floyd里面用|和&比||和&&时间缩短了将近一半!
#include <bits/stdc++.h>
using namespace std;
const int maxn=205;
const int INF=0x3f3f3f3f;
int T;
struct Edge{
int from,to,cap,flow;
};
struct Dinic{
int n,m0,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
bool vis[maxn];
int d[maxn];
int cur[maxn];
void init()
{
s=0,t=1;
int d[105][105]={0};
scanf("%d%d",&n,&m0);
edges.clear();
for(int i=0;i<=2*n+1;i++)G[i].clear();
int x,y;
for(int i=1;i<=n;i++)d[i][i]=1;
while(m0--)
{
scanf("%d%d",&x,&y);
d[x][y]=1;
}
for(int k=1;k<=n;k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
d[i][j]=d[i][j]||(d[i][k]&&d[k][j]);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
if(i!=j && d[i][j])
{
AddEdge(i*2,j*2+1,1);
}
for(int i=1;i<=n;i++)AddEdge(s,i*2,1),AddEdge(i*2+1,t,1);
}
void AddEdge(int f,int t,int c)
{
edges.push_back((Edge){f,t,c,0});
edges.push_back((Edge){t,f,0,0});
m=edges.size();
G[f].push_back(m-2);
G[t].push_back(m-1);
}
bool bfs()
{
memset(vis,0,sizeof(vis));
queue<int> Q;
Q.push(s);
d[s]=0;
vis[s]=1;
while(!Q.empty())
{
int x=Q.front();Q.pop();
for(int i=0;i<G[x].size();i++)
{
Edge& e=edges[G[x][i]];
if(!vis[e.to] && e.cap>e.flow)
{
vis[e.to]=1;
d[e.to]=d[x]+1;
Q.push(e.to);
}
}
}
return vis[t];
}
int dfs(int x,int a)
{
if(x==t || a==0)return a;
int flow=0,f;
for(int& i=cur[x];i<G[x].size();i++)
{
Edge& e=edges[G[x][i]];
if(d[x]+1==d[e.to] && (f=dfs(e.to,min(a,e.cap-e.flow)))>0)
{
e.flow+=f;
edges[G[x][i]^1].flow-=f;
flow+=f;
a-=f;
if(!a)break;
}
}
return flow;
}
int MaxFlow()
{
int flow=0;
while(bfs())
{
memset(cur,0,sizeof(cur));
flow+=dfs(s,INF);
}
return flow;
}
}ans;
int main()
{
//freopen("input.in","r",stdin);
cin>>T;
while(T--)
{
ans.init();
cout<<ans.n-ans.MaxFlow()<<"\n";
}
return 0;
}