hdu 4635 Strongly connected(强联通)
2015-10-28 21:46
351 查看
题目链接:hdu 4635 Strongly connected
解题思路
先对给定图做强联通分量,选取出度或者是入度为0的分量中点个数最少的一个,然后其它联通分量算一个,将图分成两部分,做完全图并保证两部分是之间的边均为单向边。代码
#include <cstdio> #include <cstring> #include <vector> #include <stack> #include <algorithm> using namespace std; const int maxn = 100005; typedef long long ll; stack<int> S; vector<int> G[maxn]; int dfsclock, cntscc, sccno[maxn], pre[maxn]; int dfs (int u) { int lowu = pre[u] = ++dfsclock; S.push(u); for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (!pre[v]) { int lowv = dfs(v); lowu = min(lowu, lowv); } else if (!sccno[v]) lowu = min(lowu, pre[v]); } if (lowu == pre[u]) { cntscc++; while (true) { int x = S.top(); S.pop(); sccno[x] = cntscc; if (x == u) break; } } return lowu; } void findSCC(int n) { dfsclock = cntscc = 0; memset(pre, 0, sizeof(pre)); memset(sccno, 0, sizeof(sccno)); for (int i = 1; i <= n; i++) if (!pre[i]) dfs(i); } int N, M, C[maxn], in[maxn], ot[maxn]; void init () { scanf("%d%d", &N, &M); for (int i = 1; i <= N; i++) G[i].clear(); int u, v; for (int i = 0; i < M; i++) { scanf("%d%d", &u, &v); G[u].push_back(v); } findSCC(N); } ll get(int c1) { int c2 = N - c1; return 1LL * N * (N-1) - 1LL * c1 * c2 - M; } ll solve () { if (cntscc == 1) return -1; memset(in, 0, sizeof(in)); memset(ot, 0, sizeof(ot)); memset(C, 0, sizeof(C)); for (int i = 1; i <= N; i++) { int u = sccno[i]; C[u]++; for (int j = 0; j < G[i].size(); j++) { int v = sccno[G[i][j]]; if (u == v) continue; ot[u]++, in[v]++; } } ll ret = 0; for (int i = 1; i <= cntscc; i++) { if (in[i] && ot[i]) continue; ret = max(ret, get(C[i])); } return ret; } int main () { int cas; scanf("%d", &cas); for (int kcas = 1; kcas <= cas; kcas++) { init(); printf("Case %d: %lld\n", kcas, solve()); } return 0; }
相关文章推荐
- 小米开源文件管理器MiCodeFileExplorer-源码研究(6)-媒体文件MediaFile和文件类型MimeUtils
- 小米开源文件管理器MiCodeFileExplorer-源码研究(6)-媒体文件MediaFile和文件类型MimeUtils
- 数据包 数据帧
- LintCode_主元素
- 用C++实现“按任意键继续”
- spring使用dwr异步通信
- XML就像是扩展应用范围的HTML
- delphi 数组的使用
- hdoj 1532 Drainage Ditches【最大流模板题】
- boost::bind
- 关于apache tomcat的几个版本
- const ||c
- Java堆栈详解
- c++ 程序输入参数
- 最小生成树-Prim
- IOS--导航栏
- jQuery获取Select选择的Text(非表单元素)和 Value(表单元素)(转)
- HDU 1244 Max Sum Plus Plus Plus DP
- 系统安装相关:U盘刻录(用U盘装ubuntu简要方法)
- android studio 更改背景和设置字体大小