分析:先把求出连通分量进行缩点,因为是求最多的添加边,所以可以看成两部分 x,y,只能一部分向另外一部分连边,内部的就是完全图,所以是x*(x+1)+x*y+y*(y+1)-M,只需要求出来出度或者入度为0的最少点的那个连通分量即可。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int MAXN = 1e5+5;
const int oo = 1e9;
struct Edge{int v, next;}e[MAXN];
int Head[MAXN], cnt;
void AddEdge(int u, int v)
{
e[cnt].v = v;
e[cnt].next = Head[u];
Head[u] = cnt++;
}
int dfn[MAXN], low[MAXN], Index;
int Stack[MAXN], top, inStack[MAXN];
int blg[MAXN], bnt, nblg[MAXN];///属于哪个连通分量,连通分量里面有几个点
int outEdge[MAXN], inEdge[MAXN];
void InIt(int N)
{
cnt = Index = top = bnt = 0;
for(int i=0; i<=N; i++)
{
Head[i] = -1;
dfn[i] = 0;
nblg[i] = 0;
outEdge[i] = 0;
inEdge[i] = 0;
}
}
void Tarjan(int u)
{
int v;
low[u] = dfn[u] = ++Index;
Stack[++top] = u;
inStack[u] = true;
for(int j=Head[u]; j!=-1; j=e[j].next)
{
v = e[j].v;
if( !dfn[v] )
{
Tarjan(v);
low[u] = min(low[u], low[v]);
}
else if(inStack[v] == true)
low[u] = min(low[u], dfn[v]);
}
if(low[u] == dfn[u])
{
++bnt;
do
{
v = Stack[top--];
inStack[v] = false;
blg[v] = bnt;
nblg[bnt]++;
}
while(u != v);
}
}
int main()
{
int T, t=1;
scanf("%d", &T);
while(T--)
{
int i, j, u, v, N, M;
scanf("%d%d", &N, &M);
InIt(N);
for(i=0; i<M; i++)
{
scanf("%d%d", &u, &v);
AddEdge(u, v);
}
for(i=1; i<=N; i++)
{
if( !dfn[i] )
Tarjan(i);
}
for(i=1; i<=N; i++)
for(j=Head[i]; j!=-1; j=e[j].next)
{
v = e[j].v;
if(blg[i] != blg[v])
{
inEdge[ blg[v] ]++;
outEdge[ blg[i] ]++;
}
}
int x, y=oo;
for(i=1; i<=bnt; i++)
{
if(!outEdge[i] || !inEdge[i])
y = min(y, nblg[i]);
}
x = N-y;
if(bnt == 1)
printf("Case %d: -1\n", t++);
else
printf("Case %d: %lld\n",t++, (long long)x*(x-1)+x*y+y*(y-1)-M);
}
return 0;
}