原题链接:https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2288

题意:

给你一个有向图,问你至少需要添加多少条边,使得整个图强连通。

题解:

就。。直接缩点,令缩点后入度为0的点有a个,出度为0的点有b个,答案就是max(a,b)

代码:

#include<iostream>
#include<cstring>
#include<vector>
#include<algorithm>
#include<stack>
#define MAX_N 20004
using namespace std; vector<int> G[MAX_N];
int dfn[MAX_N],low[MAX_N],ind;
bool vis[MAX_N];
stack<int> st;
bool inStack[MAX_N]; int id[MAX_N],tot=;
vector<int> newG[MAX_N];
vector<int> newrG[MAX_N]; int n,m; void init() {
for (int i = ; i <= n; i++) {
G[i].clear();
newG[i].clear();
newrG[i].clear();
}
memset(dfn, , sizeof(dfn));
memset(low, , sizeof(low));
ind = tot = ;
memset(vis, , sizeof(vis));
while (st.size())st.pop();
memset(inStack, , sizeof(inStack));
memset(id, , sizeof(id));
} void Tarjan(int u) {
dfn[u] = low[u] = ++ind;
st.push(u);
inStack[u] = ;
vis[u] = ;
for (int i = ; i < G[u].size(); i++) {
int v = G[u][i];
if (!vis[v]) {
Tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (inStack[v])
low[u] = min(low[u], dfn[v]);
}
if (low[u] == dfn[u]) {
tot++;
int t;
do {
t = st.top();
st.pop();
inStack[t] = ;
id[t] = tot;
} while (t != u);
}
} int main() {
int T;
cin.sync_with_stdio(false);
cin >> T;
while (T--) {
cin >> n >> m;
int ans = ;
init();
for (int i = ; i < m; i++) {
int u, v;
cin >> u >> v;
G[u].push_back(v);
}
for (int i = ; i <= n; i++)
if (!vis[i])Tarjan(i);
for (int u = ; u <= n; u++)
for (int i = ; i < G[u].size(); i++)
if (id[u] != id[G[u][i]]) {
newG[id[u]].push_back(id[G[u][i]]);
newrG[id[G[u][i]]].push_back(id[u]);
}
if (tot == ) {
cout << << endl;
continue;
}
int a = , b = ;
for (int u = ; u <= tot; u++) {
if (newG[u].size() == )a++;
if (newrG[u].size() == )b++;
}
cout << max(a, b) << endl;
}
return ;
}

最新文章

  1. css权威指南-基本视觉格式化(水平与垂直)
  2. OWIN系列之自己动手编写中间件
  3. Go 项目的目录结构 及 安装技巧
  4. bootstrap - 响应式标题栏
  5. Mybatis基于注解的方式访问数据库
  6. memset函数详解
  7. NSDate 刚刚、几分钟、几小时
  8. 小米手机无法打开程序报错Unable to instantiate application com.android.tools.fd.runtime.BootstrapApplication的解决办法
  9. LeetCode() Word Search II
  10. 【SQL语句】 - 在所有存储过程中查找关键字,关键字不区分大小写 [sp_findproc]
  11. Unix/Linux环境C编程入门教程(21) 各个系统HelloWorld跑起来效果如何?
  12. CSS3线性渐变linear-gradient
  13. 查看SQL Server 2008的版本及位数
  14. Adapter基本用法
  15. rails自动生成大量记录的方法
  16. 数据分析 大数据之路 四 numpy 2
  17. 导入项目的时候报错Error:Could not find com.android.support.constraint:constraint-layout:1.0.0-alpha7
  18. Confluence 6 关于嵌入的 H2 数据库
  19. Codeforces Round #425 (Div. 2) Problem A Sasha and Sticks (Codeforces 832A)
  20. 5289: [Hnoi2018]排列

热门文章

  1. Linux系统入门-Bash初识
  2. GoF23种设计模式之行为型模式之责任链模式
  3. Django之模型---ORM 多表操作
  4. 原生Ajax+springBoot实现用户登录
  5. Linux学习-核心的编译与安装
  6. Linux学习-分析登录档
  7. HDU 4781 Assignment For Princess 构造
  8. webdriver高级应用- 禁止IE的保护模式
  9. shutil——高级的 文件、文件夹、压缩包 处理模块
  10. List容器——ArrayList及常用API