POJ1236DAG转强连通图
Posted hesorchen
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ1236DAG转强连通图相关的知识,希望对你有一定的参考价值。
题目
不难得出第一问答案是,对原图tarjan缩点、转化为DAG之后入度为0的点个数。
第二问有个结论:要将DAG图转化为强连通图,需要增加的最少单向边数量为max(indegree,outdegree)。
因为强连通图中每个点对都要互相可达,那就每个点都要可进可出。
代码
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <stack>
#include <map>
using namespace std;
const int N = 105;
vector<int> edge[N];
int dfn[N], low[N], ct, cnt;
bool instack[N];
vector<int> st;
vector<int> blocks[N];
map<int, int> mp;
void tarjan(int u)
{
dfn[u] = low[u] = ++ct;
instack[u] = 1;
st.push_back(u);
for (int i = 0; i < edge[u].size(); i++)
{
int v = edge[u][i];
if (!dfn[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])
{
++cnt;
int node;
do
{
node = st.back();
st.pop_back();
instack[node] = 0;
mp[node] = cnt;
blocks[cnt].push_back(node);
} while (low[node] != dfn[node]);
}
}
int indegree[N];
int outdegree[N];
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
int v;
while (cin >> v, v)
edge[i].push_back(v);
}
for (int i = 1; i <= n; i++)
if (!dfn[i])
tarjan(i);
for (int i = 1; i <= n; i++)
{
for (int j = 0; j < edge[i].size(); j++)
{
int it = edge[i][j];
if (mp[i] == mp[it])
continue;
indegree[mp[it]] = 1;
outdegree[mp[i]] = 1;
}
}
int res1 = 0, res2 = 0;
for (int i = 1; i <= n; i++)
if (blocks[i].size())
(res1 += !outdegree[i]), (res2 += !indegree[i]);
cout << res2 << endl
<< (cnt == 1 ? 0 : max(res1, res2)) << endl;
return 0;
}
以上是关于POJ1236DAG转强连通图的主要内容,如果未能解决你的问题,请参考以下文章
[POJ1236]Network of Schools(并查集+floyd,伪强连通分量)