Strongly connected (强连通分量 Tarjan+缩点)

Strongly connected

 

Give a simple directed graph with N nodes and M edges. Please tell me the maximum number of the edges you can add that the graph is still a simple directed graph. Also, after you add these edges, this graph must NOT be strongly connected. 
A simple directed graph is a directed graph having no multiple edges or graph loops.
A strongly connected digraph is a directed graph in which it is possible to reach any node starting from any other node by traversing edges in the direction(s) in which they point. 

Input

The first line of date is an integer T, which is the number of the text cases. 
Then T cases follow, each case starts of two numbers N and M, 1<=N<=100000, 1<=M<=100000, representing the number of nodes and the number of edges, then M lines follow. Each line contains two integers x and y, means that there is a edge from x to y.

Output

For each case, you should output the maximum number of the edges you can add. 
If the original graph is strongly connected, just output -1.

Sample Input

3
3 3
1 2
2 3
3 1
3 3
1 2
2 3
1 3
6 6
1 2
2 3
3 1
4 5
5 6
6 4

Sample Output

Case 1: -1
Case 2: 1
Case 3: 15

 

题目大意:给出n点m边的有向图,求最多可以加多少条边使得图不是强连通图,如果本来就是强连通图就输出-1;

思路:n 个点之间最多有n*(n-1)条边,减去图中已经连上的m条边,可以加的边最多为ans=n*(n-1)-m,;

其中还要保证加边后的图不是强连通图,所以还要从中减去一定数量D,要使D最小;

要保证不是强连通图,即缩点后要保证不构成环,即保证一个强连通分量入度或者出度为0,所以 D=k*(n-k) (强连通分量的点数与剩余点数的乘积)

最大可加边数 ans=n*(n-1)-m-D(min);

代码:

#include
#include
#include
#include
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int N=200000+20;
const int M=200000+20;
const long long inf=1e12+20;
int first[N],dfn[N],low[N];
int in[N],out[N],color[N],vis[N],poi[N];//poi记录连通分量的点数
int tot,cnt,time;
stacks;
struct node
{
    int v,next;
}e[M];
void init() //初始化
{
    mem(first,-1);
    mem(dfn,0);
    mem(low,0);
    mem(vis,0);
    mem(color,0);
    mem(poi,0);
    mem(in,0);
    mem(out,0);
    tot=time=cnt=0;
    while(!s.empty()) s.pop();
}
void adde(int u,int v) //建边
{
    e[tot].v=v;
    e[tot].next=first[u];
    first[u]=tot++;
}
void tarjan(int u)
{
    vis[u]=1;
    s.push(u);
    dfn[u]=low[u]=++time;
    for(int i=first[u];~i;i=e[i].next)
    {
        int v=e[i].v;
        if(!dfn[v])
        {
            tarjan(v);
            low[u]=min(low[u],low[v]);
        }
        else if(vis[v])
            low[u]=min(low[u],dfn[v]);
    }
    if(low[u]==dfn[u])
    {
        cnt++;
        while(1)  
        {
            int now=s.top();
            s.pop();
            vis[now]=0;
            color[now]=cnt; 
            poi[cnt]++;
            if(now==u) break;
        }
    }
}
int main()
{
    int t,k=1;
    scanf("%d",&t);
    while(t--)
    {
        init();
        int n,m,x,y;
        scanf("%d%d",&n,&m);
        for(int i=0;i

 

你可能感兴趣的:(图连通)