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.
InputThe 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.OutputFor 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
题意:题目明显告诉了这是强连通的题,询问最多添加多少条边,结果得到的依旧不是强连通图,如果一开始就是强连通图,则输出“-1”。
题解:首先,特判的肯定先解决,依旧是tarjan算法,如果是一个强连通图,输出“-1”。然后因为该题是求最大,而且是连通图和非连通图的临界条件。于是可以yy一下最大值的情况是怎样的。因为还是tarjan然后求DAG,这是最基本的,即我们已经将原图变成DAG了,此时还不能是强连通图,则必须有一个DAG对于其他所有的DAG都只有出边而不能有入边(或者只有入边而没有出边,这是一样的),而答案就是完全图的边数(n*(n-1))- (这个特殊的DAG与外界不能相连的边数,即该DAG里的顶点个数乘以除该DAG的顶点外的所有顶点数)- (原来图本就存在的边数m)。而要想这个值最大,则这个特殊的DAG的元素必须最少(或者最大),而求DAG的元素个数就是简单的在推栈的过程中加上个计数器,并储存到一个数组里。最后的操作就只需要在出入度为0的DAG中找出元素最少的,做刚才的运算就可以了。
代码:
//Wud
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include