On the mysterious continent of Tamriel, there is a great empire founded by human.
To develope the trade, the East Empire Company is set up to transport goods from place to place.
Recently, the company wants to start their business in Solstheim, which is consists of N islands.
Luckily, there are already M sea routes.
All routes are one-way, and the i-th route can transport person and goods from island ui to vi.
Now, the company nominates you a particular job to plan some new routes to make sure that person and goods can be transported between any two islands.
Furthermore, because the neighboring regions are under attack by an increasing number of dragons, limited resources can be used to set up new routes.
So you should plan to build new routes as few as possible.
Input Format
The first line contains an integer T, indicating that there are T test cases.
For each test case, the first line includes two integers N (N≤10000) and M (M≤100000), as described above.
After that there are M lines. Each line contains two integers ui and vi.
Output Format
For each test case output one integer, represent the least number of routes required to new.
样例输入
2 4 3 1 2 2 3 3 4 4 4 1 2 1 4 3 2 3 4
样例输出
1 2
给n个点和m条有向边,问最少再加几条边使其变成强连通图。
思路:
先tarjan跑一遍,如果是强连通图就输出0。否则输出max(入度为0的点个数,出度为0的点个数)。
居然是hdu2767的原题,以前还做过。。。。
http://blog.youkuaiyun.com/zchahaha/article/details/51223516
#include <iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#define N 22000
#define M 110000
using namespace std;
struct node
{
int to,next;
}e[M];
int dfn[N],low[N],head[N],in[N],out[N],cnt,scnt,top,q[N],v[N],belong[N],n,m;
void init()
{
memset(head,-1,sizeof(head));
memset(dfn,0,sizeof(dfn));
memset(low,0,sizeof(low));
memset(in,0,sizeof(in));
memset(out,0,sizeof(out));
memset(belong,0,sizeof(belong));
cnt=scnt=top=0;
}
void add_edge(int u,int v)
{
e[cnt].to=v;
e[cnt].next=head[u];
head[u]=cnt++;
}
void tarjan(int u)
{
int t;
low[u]=dfn[u]=cnt++;
q[top++]=u;
v[u]=1;
for(int i=head[u];i+1;i=e[i].next)
{
int c=e[i].to;
if(!dfn[c])
{
tarjan(c);
low[u]=min(low[u],low[c]);
}
else if(v[c])
low[u]=min(low[u],dfn[c]);
}
if(low[u]==dfn[u])
{
scnt++;
do
{
t=q[--top];
v[t]=0;
belong[t]=scnt;
}while(t!=u);
}
}
void solve()
{
for(int i=1;i<=n;i++)
if(!dfn[i]) tarjan(i);
if(scnt==1)
{
cout<<0<<endl;
return ;
}
for(int i=1;i<=n;i++)
for(int j=head[i];j+1;j=e[j].next)
{
int t=e[j].to;
if(belong[i]!=belong[t])
{
in[belong[t]]++;
out[belong[i]]++;
}
}
int a=0,b=0;
for(int i=1;i<=scnt;i++)
{
if(in[i]==0) a++;
if(out[i]==0) b++;
}
cout<<max(a,b)<<endl;
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>m;
init();
for(int i=0;i<m;i++)
{
int u,v;
scanf("%d%d",&u,&v);
add_edge(u,v);
}
solve();
}
}