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

## [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;
}

#### Codeforces Round #444 (Div. 2)-贪心&尺取-Ratings and Reality Shows

2017-11-11 20:11:11

#### Codeforces Round #446 (Div. 2) D. Gluttony

2017-11-18 21:07:25

#### CF-Codeforces Round #483 (Div. 2)-D-XOR-pyramid

2018-05-16 01:15:04

#### Codeforces Round #426 (Div. 2) D. The Bakery（DP+线段树）

2017-07-31 09:16:44

#### Educational Codeforces Round 36 (Rated for Div. 2) 题解

2018-01-13 23:16:24

#### Codeforces Round #471 (Div. 2)

2018-03-27 23:23:41

#### CF-Codeforces Round #485 (Div. 2)-E-Petr and Permutations

2018-05-30 17:33:35

#### Codeforces Round #402 (Div. 2)C. Dishonest Sellers【贪心】这个贪心好水啊....

2017-02-27 13:07:44

#### Codeforces Round #476 (Div. 2) [Thanks, Telegram!] D - Single-use Stones（思维）

2018-04-27 00:50:37

#### Codeforces Round #382 (Div. 2)D. Taxes（数论知识)

2016-11-28 11:41:58