2020牛客多校第五場補題
阿新 • • 發佈:2020-07-25
E Bogo Sort
置換求環 + 大整數 + lcm
就是求出這個置換有多少環,然後對這些環的大小進行求lcm
對於置換求環
#include <iostream> #include <cstdio> using namespace std; const int N = 1e5 + 5; int p[N], ans[N], cnt; bool vis[N]; int main(){ int n; scanf("%d", &n); for(int i = 1; i <= n; i++) cin >> p[i]; // 置換 for(int i = 1; i <= n; i++) { if(vis[i]) continue; int tmp = i, tot = 0; while(vis[tmp] == 0) { //沿著置換遍歷 vis[tmp] = 1; tmp = p[tmp]; tot++; } ans[++cnt] = tot; // 第cnt個環的大小 } return 0; }
好像在java裡,new一個BIgInteger比較慢,但是直接呼叫one,ten的大整數快
import java.math.BigInteger; import java.util.*; public class Main { static int p[] = new int[100010]; static int num[] = new int[100010]; static boolean vis[] = new boolean[100010]; public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(), cnt = 0; for(int i = 1; i <= n; i++) { p[i] = in.nextInt(); } BigInteger mod = BigInteger.ONE; for(int i = 1; i <= n; i++) { mod = mod.multiply(BigInteger.TEN); if(vis[i]) continue; int tmp = i, tot = 0; while(!vis[tmp]) { vis[tmp] = true; tmp = p[tmp]; tot++; } num[++cnt] = tot; } BigInteger ans = new BigInteger(String.valueOf(num[1])); for(int i = 1; i <= cnt; i++) { BigInteger g = ans.gcd(new BigInteger(String.valueOf(num[i]))); ans = ans.multiply(new BigInteger(String.valueOf(num[i]))); ans = ans.divide(g); } System.out.println(ans.mod(mod)); in.close(); } }