codeforces 873 D. Merge Sort(分治)

题目链接:http://codeforces.com/contest/873/problem/D

 

题解:这题挺简单的,除了一开始算作是调用到一次,然后每次执行操作时都会调用2次,所以最多调用几次就很好算了,而且只有奇数调用次数才合理。然后就是类似分治的思想,每次dfs二分过去,发现调用次数不够就交换mid和mid-1那么就会再被调用2次。

#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <cstdio>
using namespace std;
const int M = 1e5 + 10;
int a[M] , cnt , n , k , tot;
void dfs(int l , int r) {
    if(l == r - 1) return ;
    if(cnt == k) return ;
    int mid = (l + r) >> 1;
    swap(a[mid] , a[mid - 1]);
    cnt += 2;
    dfs(l , mid);
    dfs(mid , r);
}
void get_tot(int l , int r) {
    int mid = (l + r) >> 1;
    if(l == r - 1) return ;
    tot += 2;
    get_tot(l , mid);
    get_tot(mid , r);
}
int main() {
    scanf("%d%d" , &n , &k);
    for(int i = 0 ; i < n ; i++) a[i] = i + 1;
    tot = 1;
    get_tot(0 , n);
    if(k % 2 && k <= tot) {
        cnt = 1;
        dfs(0 , n);
        for(int i = 0 ; i < n ; i++) {
            printf("%d " , a[i]);
        }
        puts("");
    }
    else {
        printf("-1\n");
    }
    return 0;
}

 

posted @ 2017-10-14 08:44  Gealo  阅读(162)  评论(0编辑  收藏  举报