zoukankan      html  css  js  c++  java
  • Codefoces 432C Prime Swaps(数论+贪心)

    版权声明:本文为博主原创文章,未经博主同意不得转载。

    https://blog.csdn.net/u011328934/article/details/26094917

    题目连接:Codefoces 432C Prime Swaps

    题目大意:给出一个序列。长度为n,要求用5n以内的交换次数使得序列有序。而且交换的i,j两个位置的数时要满足,ji+1为素数。

    解题思路:a数组为相应的序列,b数组为相应的有序序列,p为相应数的位置。每次从有序序列最小的位置開始,该为必须放b[i]才对。所以p[b[i]]=i,否则就要将b[i]尽量往前换,直到换到i的位置为止。

    哥德巴赫猜想:不论什么一个大于5的数都能够写成三个质数之和。

    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    
    using namespace std;
    const int N = 1e5+5;
    
    int n, a[N], b[N], p[N], v[N], r[5*N][2];
    
    void init () {
        memset(v, 0, sizeof(v));
    
        for (int i = 2; i <= n; i++) {
            if (v[i])
                continue;
    
            for (int j = i * 2; j <= n; j += i)
                v[j] = 1;
        }
    
        for (int i = 1; i <= n; i++) {
            scanf("%d", &a[i]);
            b[i] = a[i];
            p[a[i]] = i;
        }
        sort(b+1, b+n+1);
    }
    
    int solve () {
        int c = 0;
    
        for (int i = 1; i <= n; i++) {
            while (p[b[i]] != i) {
                for (int j = i; j < p[b[i]]; j++) {
                    if (!v[p[b[i]] - j + 1]) {
                        r[c][1] = p[b[i]];
                        r[c++][0] = j;
    
                        int t = p[b[i]];
                        p[b[i]] = j;
                        p[a[j]] = t;
                        swap(a[j], a[t]);
                        break;
                    }
                }
            }
        }
        return c;
    }
    
    int main () {
        scanf("%d", &n);
        init();
        int c = solve();
    
        printf("%d
    ", c);
        for (int i = 0; i < c; i++)
            printf("%d %d
    ", r[i][0], r[i][1]);
        return 0;
    }
查看全文
  • 相关阅读:
    Json对象与Json字符串互转(4种转换方式)
    Web.config配置文件详解
    jQuery BlockUI Plugin Demo 6(Options)
    jQuery BlockUI Plugin Demo 5(Simple Modal Dialog Example)
    jQuery BlockUI Plugin Demo 4(Element Blocking Examples)
    jQuery BlockUI Plugin Demo 3(Page Blocking Examples)
    jQuery BlockUI Plugin Demo 2
    <configSections> 位置引起的错误
    关于jQuery的cookies插件2.2.0版设置过期时间的说明
    jQuery插件—获取URL参数
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10768051.html
  • Copyright © 2011-2022 走看看