1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
|
#include <bits/stdc++.h> #define all(vec) vec.begin(),vec.end() #define pb push_back #define SZ(a) ((int) a.size()) #define FOR(i, a, b) for (int i = (a); i <= (b); ++i) #define ROF(i, a, b) for (int i = (a); i >= (b); --i) #define debug(var) cerr << #var <<":"<<var<<"\n"; #define lson(var) (var<<1) #define rson(var) ((var<<1)+1) #define V vector
using namespace std;
using ll = long long;using ull = unsigned long long; using DB=double;using LD=long double;
using pdd = pair<DB,DB>;using plb = pair<ll,bool>; using pll = pair<ll,ll>;using vll=vector<ll>;using vb=vector<bool>; using arr3 = array<ll,3> ;using arr2 = array<ll,2>; constexpr ll MAXN=static_cast<ll>(5e5)+10,INF=static_cast<ll>(1e17)+9; constexpr ll MAXM=(ll)1e6+10;constexpr ll MAXV=(ll)1e6+10; constexpr ll mod=998244353; constexpr double eps=1e-8;const double pi=acos(-1.0);
ll N,M,Q,X,K,T,lT,A[MAXN];
struct DSU { vector < int > fa, siz; int ln; DSU(int n) { ln = n; fa.resize(ln + 5, 0), siz.resize(ln + 5, 0); FOR(i, 1, n) { fa[i] = i; siz[i] = 1; } } int find(int x) { while (fa[x] != x) { x = fa[x]; fa[x] = fa[fa[x]]; } return x; } bool same(int x, int y) { return find(x) == find(y); } bool merge(int x, int y) { x = find(x); y = find(y); if (x == y) { return false; } siz[x] += siz[y]; fa[y] = x; return true; } int size(int x) { return siz[find(x)]; } int countFa() { int res = 0; FOR(i, 1, ln) { if (fa[i] == i) ++res; } return res; } }; ll binpow(ll a,ll k){ ll res=1; a%=mod; while(k>0){ if((k&1)==1) res=a*res%mod; a=a*a%mod; k>>=1; } return res; } inline void __(){ cin>>N; DSU fa(N); FOR(i,1,N){ cin>>A[i]; fa.merge(i,A[i]); } vb vis(N+5,0); vll cnt(3,0),mul(3,1); FOR(i,1,N){ if(vis[fa.find(i)]) continue; vis[fa.find(i)]=true; ll siz=fa.size(i); if(siz==2) continue; cnt[siz%2]++; if(siz%2) mul[siz%2]*=siz; } ll ans=0; if(cnt[1]==2){ ans=binpow(2,cnt[0])*mul[1]; ans%=mod; }else if(cnt[1]>=4){ cout<<0<<"\n"; return; }else{ vis.assign(N+5,0); FOR(i,1,N){ if(vis[fa.find(i)]) continue; vis[fa.find(i)]=true; ll siz=fa.size(i); if(siz==2){ ans+=binpow(2,cnt[0]); ans%=mod; }else{ ll t=siz*siz%mod*binpow(4,mod-2);t%=mod; ans+=binpow(2,cnt[0]-1)*t; ans%=mod; } } } ans%=mod; if(ans<0) ans+=mod; cout<<ans<<"\n"; }
int main() { ios::sync_with_stdio(false); cin.tie(0);cout.tie(0); cin>>lT; while(lT--) __(); return 0; }
|