Proving Equivalences UVA - 12167
题意:
a,b,c,d。注意每次证明都是双向的,a
↔
\leftrightarrow
↔b, 。。b
↔
\leftrightarrow
↔c,。。c
↔
\leftrightarrow
↔d因此一共完成了6
次推导。另一种证明方法是a
→
\rightarrow
→b, 。。b
→
\rightarrow
→c,。。c
→
\rightarrow
→d。。d
→
\rightarrow
→a.只需4
次。
给你n个命题。现给出m次推导,你至少需要几次推导才能完成整个证明?
思路:
- 可以把一次推导,抽象成一条边。
- 可以用第二种证明方法。
- 首先可以知道的是:已经可以完成的证明,肯定在一个 强连通分量里。那么对这些强连通分量进行缩点。
- 问题就转换成了把一个DAG构造成一个强连通分量。做法也很容易,算出缩点后每个点的 入度 和 出度。
- ans是max(in0,out0)(入度为0的点,和出度为0的点取max)
反思:
一般强连通分量求完就是缩点。
- 本题注意只有一个强连通分量的情形。此时对于这个点,不管入度和出度都为0.按照上面的算法,ans=1.(可是实际的ans=0,所以特判一下即可)。
AC
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <stack>
#define mst(x,a) memset(x,a,sizeof(x))
#define pb push_back
#define fzhead EDGE(int _to, int _next)
#define fzbody to(_to), next(_next)
#define fori(i,x,y) for(int i=(x); i<(y); i++)
#define For(i,x,y) for(int i=(x); i<=(y); i++)
using namespace std;
const int maxn=2e4+10;
const int maxm=5e4+10;
struct EDGE{
int to,next;
EDGE(){}
fzhead:fzbody{}
}e[maxm];
int low[maxn],dfn[maxn],sccno[maxn],dfs_clock,scc_cnt;
stack<int>s;
int tot,head[maxm];
void add(int bg, int to){
e[tot]=EDGE(to,head[bg]);
head[bg]=tot++;
}
void tarjan(int u){
dfn[u]=low[u]=++dfs_clock;
s.push(u);
for(int i=head[u]; i!=-1; i=e[i].next){
int v=e[i].to;
if(!dfn[v]){
tarjan(v);
low[u]=min(low[u],low[v]);
}else if(!sccno[v])low[u]=min(low[u],dfn[v]);
}
if(dfn[u]==low[u]){
scc_cnt++;
int x;
do{
x=s.top();s.pop();
sccno[x]=scc_cnt;
}while(x!=u);
}
}
int n,m;
int in[maxn],out[maxn];
void init(){
mst(head,-1);mst(low,0);
mst(dfn,0);mst(sccno,0);
dfs_clock=scc_cnt=tot=0;
tot=2;
cin>>n>>m;
For(i,1,m){
int u,v;
cin>>u>>v;
add(u,v);
}
while(!s.empty())s.pop();
}
int main()
{
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int tt;cin>>tt;
while(tt--){
init();
For(u,1,n)if(!dfn[u])dfs_clock=0,tarjan(u);
//cout<<scc_cnt<<endl;
mst(in,0);mst(out,0);
For(u,1,n){
for(int i=head[u]; i!=-1; i=e[i].next){
int v=e[i].to;
if(sccno[u]==sccno[v])continue;
out[sccno[u]]++,in[sccno[v]]++;
}
}
int ans1=0,ans2=0;
For(i,1,scc_cnt){
if(in[i]==0)ans1++;
if(out[i]==0)ans2++;
}
int ans=max(ans1,ans2);
if(scc_cnt==1)ans=0;
cout<<ans<<endl;
}
return 0;
}