zoukankan      html  css  js  c++  java
  • ural 1024. Permutations

    一开始直接模拟,果断超时了,后来上网查了查,是组合数学中的置换群。

     本题求经过多少次置换P能变成初始状态。

     对于任意一个[1,n]的数字,经过多次置换后一定可以变会初始状态,

       而且置换的次数不会超过n。

    对于第i个数,模拟计算出其置换周期,记为ai,答案就是所有ai的最小公倍数。

         1 2 3 4 5

         4 1 5 2 3

    次数:3 3 2 3 2,最小公倍数6.

     1 #include <iostream>
     2 #include <cstdio>
     3 int gcd(int a, int b)
     4 {
     5     if (b == 0)
     6         return a;
     7     else
     8         return gcd(b, a % b);
     9 }
    10 int lcm(int a, int b)
    11 {
    12     return a / gcd(a, b) * b;
    13 }
    14 int rota(int *f, int i)
    15 {
    16      int num = 1;
    17      int t = f[i];
    18      while (f[i] != f[t])
    19      {
    20            t = f[t];
    21            ++num;
    22      }
    23      return num;
    24 }
    25     
    26 int main()
    27 {
    28     int n;
    29     scanf("%d", &n);
    30     int f[n+1];
    31     for (int i = 1; i <= n; ++i)
    32     {
    33         scanf("%d", &f[i]);
    34     }
    35     int ans = 1;
    36     for (int i = 1; i <= n; ++i)
    37     {
    38         int num = rota(f, i);
    39         ans = lcm(ans, num);
    40     }
    41     printf("%d\n", ans);
    42     //system("pause");
    43     return 0;
    44 }
  • 相关阅读:
    layui使用iconfont
    MySQL&MyBatis 时间处理的配合
    Jira客户端
    同级div设置display:inline-block,父级div强制不换行
    Spring RestController 请求参数详解
    Mybatis映射文件
    Redis分布式锁
    Netty1
    Maven工程打成一个jar包
    Maven 工程读取resource下的文件
  • 原文地址:https://www.cnblogs.com/PegasusWang/p/3003712.html
Copyright © 2011-2022 走看看