1863G - Swaps - CodeForces Solution


combinatorics graphs math

Please click on ads to support us..

C++ Code:

#include <bits/stdc++.h>

using namespace std;

#define ll long long
#define pb push_back

const int N = 1e6 + 100;
const ll MOD = 1e9 + 7;

int n, a[N], in[N], bio[N];

inline ll mul(ll x, ll y){
	return (x * y) % MOD;
}

inline ll add(ll x, ll y){
	if (x + y >= MOD) return (x + y - MOD);
	return (x + y);
}

inline ll diff(ll x, ll y){
	if (x < y) return (x - y + MOD);
	return (x - y);
}

int main(){
	ios_base::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	
	cin >> n;
	for (int i = 1; i <= n; ++i){
		cin >> a[i]; ++in[a[i]];
	}
	
	vector<int> cycle; int cnt = 1;
	for (int i = 1; i <= n; ++i){
		if (bio[i] > 0) continue;
		int x = i;
		while (bio[x] == 0)
			bio[x] = cnt, x = a[x];
		if (bio[x] == cnt)
			cycle.pb(x);
		++cnt;
	}
	
	ll sol = 1; memset(bio, 0, sizeof(bio));
	for (int x: cycle){
		int y = x, deg_sum = 0;
		ll M = 1;
		while (!bio[y]){
			M = mul(M, in[y] + 1);
			deg_sum += in[y];
			bio[y] = 1; y = a[y];
		}
		sol = mul(sol, diff(M, deg_sum));
	}
	
	for (int i = 1; i <= n; ++i){
		if (!bio[i]) sol = mul(sol, in[i] + 1);
	}
	
	cout << sol;
	
	return 0;
}


Comments

Submit
0 Comments
More Questions

702C - Cellular Network
1672C - Unequal Array
1706C - Qpwoeirut And The City
1697A - Parkway Walk
1505B - DMCA
478B - Random Teams
1705C - Mark and His Unfinished Essay
1401C - Mere Array
1613B - Absent Remainder
1536B - Prinzessin der Verurteilung
1699B - Almost Ternary Matrix
1545A - AquaMoon and Strange Sort
538B - Quasi Binary
424A - Squats
1703A - YES or YES
494A - Treasure
48B - Land Lot
835A - Key races
1622C - Set or Decrease
1682A - Palindromic Indices
903C - Boxes Packing
887A - Div 64
755B - PolandBall and Game
808B - Average Sleep Time
1515E - Phoenix and Computers
1552B - Running for Gold
994A - Fingerprints
1221C - Perfect Team
1709C - Recover an RBS
378A - Playing with Dice