http://acm.hdu.edu.cn/showproblem.php?pid=4635
题意:给出n个点和m条边,问最多能添加几条边使得图不是一个强连通图。如果一开始强连通就-1.思路:把图分成x个强连通分量之后,每个强连通分量最大的边数是n*(n-1),然后考虑和其他强连通分量相连的情况:即把分量a的所有点都连向分量b的所有点,而b不连a,这样就可以让图不是强连通的。可以把整个图分成两个强连通分量a和b分别有i和j个点,其中i+j=n,那么答案就是n*(n-1)-m-i*j。所以求出最小的i*j就可以找到答案了。
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <vector>
#include <stack>
using namespace std;
#define N 100010
struct node
{
int v, next, u;
}edge[N]; int n, tot, cnt, num, head[N], dfn[N], low[N], belong[N], in[N], out[N], deg[N], tol[N], e[N];
bool vis[N];
stack<int> sta; void init()
{
tot = ;
num = ;
cnt = ;
while(!sta.empty()) sta.pop();
memset(head, -, sizeof(head));
memset(vis, false, sizeof(vis));
memset(low, , sizeof(low));
memset(dfn, , sizeof(dfn));
memset(belong, , sizeof(belong));
memset(in, , sizeof(in));
memset(out, , sizeof(out));
memset(deg, , sizeof(deg));
memset(tol, , sizeof(tol));
memset(e, , sizeof(e));
} void add(int u, int v)
{
edge[tot].u = u; edge[tot].v = v; edge[tot].next = head[u]; head[u] = tot++;
} void tarjan(int u)
{
vis[u] = ; sta.push(u);
dfn[u] = low[u] = ++cnt;
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if(!dfn[v]) {
tarjan(v);
if(low[v] < low[u]) low[u] = low[v];
} else if(vis[v]) {
if(dfn[v] < low[u]) low[u] = dfn[v];
}
}
if(low[u] == dfn[u]) {
++num;
int top = -;
while(top != u) {
top = sta.top(); sta.pop();
vis[top] = ;
belong[top] = num;
}
}
} bool cmp(const int &a, const int &b)
{
if(out[a] != ) return false;
if(out[b] != ) return true;
return tol[a] < tol[b];
} int main()
{
int t, cas = ;
scanf("%d", &t);
while(t--) {
int n, m;
scanf("%d%d", &n, &m);
init();
for(int i = ; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v);
add(u, v);
deg[u]++; deg[v]++;
}
for(int i = ; i <= n; i++) {
if(!dfn[i]) tarjan(i);
}
printf("Case %d: ", cas++);
if(num == ) {
puts("-1"); continue;
}
// printf("~~~\n");
for(int u = ; u <= n; u++) {
for(int i = head[u]; ~i; i = edge[i].next) {
int v = edge[i].v;
if(belong[u] != belong[v]) {
in[belong[v]]++;
out[belong[u]]++;
}
}
}
long long sum = (long long)n * (n - ) - m;
for(int i = ; i <= n; i++) {
int tmp = belong[i];
tol[tmp]++;
}
long long ans = ;
for(int i = ; i <= num; i++) {
if(!in[i] || !out[i]) {
ans = max(ans, sum - (long long)(n - tol[i]) * tol[i]);
}
}
printf("%I64d\n", ans);
}
return ;
} /*
1
6 7
1 2
2 3
3 1
4 5
5 6
6 4
6 1
*/