hdu acm 4635 Strongly connected

Problem Description
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
tarjan算法。。。
解题关键:要使添加最多的边使得整张图仍为非强连通分量,最后连成的模样一定是只剩下2个强连通分量(X和Y),只需要找出入度=0或出度=0的联通分量中联通分量点数最小的那个。(X+Y=n,只有X与Y差距最大时,X*Y最小。)n个顶点最多可以连n*(n-1)条边。要去掉原来有的m条边。
ans=n*(n-1)-m-X*Y;
#include
using namespace std;
#include
#include
#include
#define maxn 0x7fffffff
int n,m,instack[100010],stackn[100010];
int low[100010],DFN[100010],head[100010];
int f,top,scnt,cnt,Belong[100010];
long long num[100010];
struct node
{
    int e,next;
}edge[100010];
void add(int s,int e)
 {
     edge[f].e=e;
     edge[f].next=head[s];
     head[s]=f++;
 }
void tarjan(int s)
 {
     int t,k,i;
     DFN[s]=low[s]=++cnt;
     stackn[top++]=s;
     instack[s]=1;
     for(i=head[s];i!=-1;i=edge[i].next)
     {
         k=edge[i].e;
         if(!DFN[k])
         {
             tarjan(k);
             low[s]=min(low[k],low[s]);
         }
         else if(instack[k])
         {
             low[s]=min(low[s],DFN[k]);
         }
     }
     if(low[s]==DFN[s])
     {
         scnt++;
         num[scnt]=0;
         do
         {
             t=stackn[--top];
             Belong[t]=scnt;
             num[scnt]++;
             instack[t]=0;
         }
         while(s!=t);
     }
 }
int main()
{
    int t,i,a,b,j,h,k;
    long long s1,ans,h1;
    scanf("%d",&t);
    for(j=1;j<=t;j++)
    {
        scanf("%d %d",&n,&m);
        memset(head,-1,sizeof(head));
        f=1;
        for(i=0;i

你可能感兴趣的:(强连通分量(tarjan算法))