# [Codeforces Round #369 (Div. 2)D. Directed Roads]Tarjan强连通分量+组合计数

480人阅读 评论(0)

## [Codeforces Round #369 (Div. 2)D. Directed Roads]Tarjan强连通分量+组合计数

ans=2ti=1scc(2numi2)

Tarjan算法直接套kuangbin的模板了~~。

#include <bits/stdc++.h>
using namespace std;

#define FIN             freopen("input.txt","r",stdin)
#define FOUT            freopen("output.txt","w",stdout)
#define fst             first
#define snd             second

typedef __int64 LL;
//typedef long long LL;
typedef pair<int, int> PII;

const int MAXN = 2e5 + 5;
const LL MOD = 1e9 + 7;

int N, M, K;
struct Edge {
int v, next;
Edge() {}
Edge(int v, int next) : v(v), next(next) {}
} edges[MAXN];
int Low[MAXN], DFN[MAXN], Stack[MAXN], Belong[MAXN];
int Index, top;
int scc;
bool Instack[MAXN];
int num[MAXN];
int par[MAXN], blocks;

void init() {
ESZ = 0;
blocks = N;
memset(par, -1, sizeof(par));
}
void add_edge(int u, int v)  {
}
int Find(int x) {
return -1 == par[x] ? x : (par[x] = Find(par[x]));
}
void Union(int x, int y) {
x = Find(x),  y = Find(y);
if(x != y) par[y] = x, blocks --;
}
LL quick_pow(LL a, LL b, LL mod) {
LL ret = 1;
while(b) {
if(b & 1) ret = ret * a % mod;
a  = a * a % mod;
b >>= 1;
}
return ret;
}
void Tarjan(int u) {
int v;
Low[u] = DFN[u] = ++Index;
Stack[top++] = u;
Instack[u] = true;
for(int i = head[u]; ~i; i = edges[i].next) {
v = edges[i].v;
if( !DFN[v] ) {
Tarjan(v);
if( Low[u] > Low[v] )Low[u] = Low[v];
} else if(Instack[v] && Low[u] > DFN[v])
Low[u] = DFN[v];
}
if(Low[u] == DFN[u]) {
scc++;
do {
v = Stack[--top];
Instack[v] = false;
Belong[v] = scc;
num[scc]++;
} while(v != u);
}
}
void solve() {
memset(DFN, 0, sizeof(DFN));
memset(Instack, false, sizeof(Instack));
memset(num, 0, sizeof(num));
Index = scc = top = 0;
for(int i = 1; i <= N; i++)
if(!DFN[i]) Tarjan(i);
LL ans = 1;
for(int i = 1; i <= scc; i++) {
LL x = (quick_pow(2LL, (LL)num[i],  MOD) -  2 +  MOD) % MOD;
x = max(x, 1LL);
ans = x * ans % MOD;
}
ans = ans * quick_pow(2LL, (LL)scc - blocks, MOD)  % MOD;
printf("%I64d\n", ans);
}
int main() {
#ifndef ONLINE_JUDGE
FIN;
#endif // ONLINE_JUDGE
int u, v;
while(~scanf("%d", &N)) {
init();
for (u = 1; u <= N; u++) {
scanf("%d", &v);
Union(u, v);
}
solve();
}
return 0;
}
1
0

个人资料
• 访问：307827次
• 积分：5872
• 等级：
• 排名：第5194名
• 原创：273篇
• 转载：8篇
• 译文：0篇
• 评论：45条
友情链接
最新评论