hdu2767—
題意:
給你一個有向圖,問你在圖中最少要加多少條邊能使得該圖變成一個強連通圖.
分析:
首先我們求出該圖的各個強連通分量,然後把每個強連通分量看出一個點(即縮點),然後我們得到了一個有向無環圖(DAG).
對於一個DAG,我們需要添加max(a,b)條邊才能使其強連通.其中a爲DAG中出度爲0的點總數,b爲DAG中入度爲0的點總數.
注意特殊情況:如果圖已經強連通了,我們需要添加的邊是0條,而不是1條.
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
#include<vector>
using namespace std;
const int maxn=20000+10;
int n,m;
vector<int> G[maxn];
stack<int> S;
int dfs_clock,scc_cnt;
int pre[maxn],low[maxn],sccno[maxn];
bool in0[maxn],out0[maxn];
void dfs(int u)
{
pre[u]=low[u]=++dfs_clock;
S.push(u);
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(!pre[v])
{
dfs(v);
low[u]=min(low[u],low[v]);
}
else if(!sccno[v])
low[u]=min(low[u],pre[v]);
}
if(low[u]==pre[u])//強連通分量起點
{
scc_cnt++;
while(true)
{
int x= S.top(); S.pop();
sccno[x]=scc_cnt;
if(x==u) break;
}
}
}
void find_scc(int n)
{
scc_cnt=dfs_clock=0;
memset(pre,0,sizeof(pre));
memset(sccno,0,sizeof(sccno));
for(int i=0;i<n;i++)
if(!pre[i]) dfs(i);
}
int main()
{
int T; scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=0;i<n;i++) G[i].clear();
while(m--)
{
int u,v;
scanf("%d%d",&u,&v);
u--, v--;
G[u].push_back(v);
}
find_scc(n);
for(int i=1;i<=scc_cnt;i++) in0[i]=out0[i]=true;
for(int u=0;u<n;u++)
{
for(int i=0;i<G[u].size();i++)
{
int v=G[u][i];
if(sccno[u] != sccno[v]) out0[sccno[u]]=in0[sccno[v]]=false;
}
}
int a=0,b=0;
for(int i=1;i<=scc_cnt;i++)
{
if(in0[i]) a++;
if(out0[i]) b++;
}
int ans=max(a,b);
if(scc_cnt==1) ans=0;
printf("%d\n",ans);
}
return 0;
}
2.poj2762
https://blog.csdn.net/animalcoder/article/details/79747595
強連通+拓撲排序。還沒看。。。
3.poj2186
translation:
給定若干頭牛和每頭牛之間的關係,若牛A認爲牛B受歡迎,牛B認爲牛C受歡迎。則牛A認爲牛C受歡迎。求牛羣中總共有多少頭
牛收到所有牛的歡迎。
solution:
首先求強聯通分量,求完之後可以將其縮點後的圖看成一個有向無環圖。根據強聯通分量的性質,所求的答案肯定是一個強聯通分量
中點的個數。那麼這個強聯通分量必定是縮點後有向無環圖中出度爲0的那個點(分量)。
ps:題目應該保證了一定有一頭牛是受到所有牛的歡迎的。
4。poj2553.
這道題我覺得有坑。
題目讓求的是:如果點v能到達u點,那麼u點也要能到達v點.
求這些點的個數。
首先,強連通分量裏的所有點一定是兩兩可達的。但是縮點後會出現出度大於0這種存在,也就是這個連通分量裏的所有點都能通過這個出度到達其他的。這樣這些點都不能滿足要求了。
所以問題轉化爲求出度爲0的強連通分量裏點的總個數。
https://blog.csdn.net/u013480600/article/details/32110575
5.
https://blog.csdn.net/su20145104009/article/details/70854526
給你一個DAG(有向無環)圖,問最多添加多少條邊後此DAG圖依然是不是強連通圖。