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;
    }
查看全文
  • 相关阅读:
    Failed to rename HdfsNamedFileStatus
    C#多线程编程(4)--异常处理+前三篇的总结
    React Native =>(箭头函数)
    React Native undefined和null
    React Native 生命周期
    React Native Invariant Violation: Text strings must be rendered within a <Text> component.
    React Native 布局 justifyContent、alignItems、alignSelf、alignContent
    React Native 实现垂直水平居中(justifyContent、alignItems)
    React Native TypeError:undefined is not an object
    React Native 自定义动态标签
  • 原文地址:https://www.cnblogs.com/ldxsuanfa/p/10768051.html
  • Copyright © 2011-2022 走看看