第十四届华中科技大学程序设计竞赛 F:Sorting Trees

链接: https://www.nowcoder.com/acm/contest/106/F
来源:牛客网

It’s universally acknowledged that there’re innumerable trees in the campus of HUST.

One day the tree manager of HUST asked you to sort N trees increasing by their heights a i. Because you were a warm-hearted and professional programmer, you immediately wrote the  Bubble Sort to finish the task. However, you were so tired that made a huge mistake:
for(int i=1;i<n;i++)
    for(int j=1;j<=n-i;j++)
         if(a[j+k]<a[j])swap(a[j+k],a[j]);
Usually k=1 is the normal  Bubble Sort. But you didn't type it correctly. When you now realize it, the trees have been replanted. In order to fix them you must find the first place that goes wrong, compared with the correctly sorted tree sequence.

If every trees are in their correct places then print -1. And you should know k can be equal to 1 which means you didn't make any mistake at all. Also you don't need to consider the part j+k beyond n.

输入描述:

 
 
The first line contains two integers N and K as described above.
Then the next line are N integers indicating the unsorted trees.

输出描述:

A integer in a single line, indicating the first place that goes wrong. Or -1 means no mistake.
#include <bits/stdc++.h>
 
using namespace std;
const int N = 1E5 + 7;
int a[N];
bool vis[N];
int b[N];
int main()
{
    int n, k;
    scanf("%d %d", &n, &k);
    for(int i = 1;i <= n;i ++) {
        scanf("%d", &a[i]);
    }
    if(k == 0) {
        for(int i = 1;i <= n;i ++) b[i]=a[i];
        sort(a+1,a+1+n);
        int pos=-1;
        for(int i = 1;i <= n;i ++) {
            if(a[i] != b[i]) {
                pos = i;
                break;
            }
        }
        return !printf("%d\n", pos);
    }
    vector<vector<pair<int,int> > >  v;
    for(int i = 1;i <= n;i ++) {
        if(vis[i]) continue;
        vector<pair<int,int> > tmp;
        vector<int> pos;
        for(int j = i;j <= n;j += k) {
            vis[j] = 1;
            pos.push_back(j);
            tmp.push_back(make_pair(a[j], j) );
        }
        if(!tmp.empty()) {
            sort(tmp.begin(), tmp.end());
            for(int j = 0;j < pos.size();j ++) {
                tmp[j].second = pos[j];
            }
            v.push_back(tmp);
        }
    }
    vector<int> b(n+1);
    for(int i = 0;i < v.size();i ++) {
        for(int j = 0;j < v[i].size();j ++) {
            b[v[i][j].second] = v[i][j].first;
        }
    }
    sort(a+1, a+1+n);
    int pos = -1;
    for(int i = 1;i <= n;i ++) {
        if(a[i] != b[i]) {
            pos = i;
            break;
        }
    }
    printf("%d\n", pos);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36876305/article/details/80151563