Gym - 101670H Dark Ride with Monsters(CTU Open Contest 2017 贪心)

题目:

A narrow gauge train drives the visitors through the sequence of chambers in the Dark Ride attraction. The chambers are occupied by IT monsters which are specially programmed to scare the visitors in various wicked ways. There is one monster in each chamber. For strange and obscure reasons, some of the monsters might have been installed in wrong chambers. The task of Freddie and Morcia, who themselves are employees and not monsters, is to reinstall the monsters in the correct chambers.

To avoid any additional confusion or threat, Freddie and Morcia work in episodes. In one episode, they choose two distinct chambers. Freddie picks the monster in one of the chambers and transports it to other chamber, while Morcia picks the monster in the other chamber and transports it to the chamber from which Freddie has just picked his monster. Thus, Freddie and Morcia effectively swap the monsters in two chambers during one episode. After some number of episodes, all monsters should be placed in correct chambers. Swapping monsters is a tedious task. Quite understandably, Freddie and Morcia want to minimize the number of episodes.

Input Specification:

There are more test cases. Each test case consists of two lines. The first line contains one integer N (1 ≤ N ≤ 2 · 105 ) specifying the number of chambers. The chambers are labeled 1, 2, . . . , N and also the monsters are labeled 1, 2, . . . , N. The label of each chamber should coincide with the label of a monster correctly installed in it. The second line contains N labels of the monsters which are currently installed in the chambers. The monster denoted by the first label on the line is installed in the chamber 1, the monster denoted by the second label on the line is installed in the chamber 2, etc.

Output Specification:

For each test case, print a single line with one integer denoting the minimum number of episodes required to install the monsters in correct chambers.

题意:

求给出的一串序列,最少经过多少步可以,转换为严格的升序。转换的规则是每次只能交换两个数的位置。

思路:

每次交换都要至少确定一个数的位置,这样遍历一遍给出的序列就ok了。其实某些情况下,越往后交换的次数是越少的,因为前边的交换可能确定了两个数的位置。

代码:

 

#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int maxn = 2e5+10;
int pos[maxn],m[maxn];

int main(){
    int n;
    while(scanf("%d",&n)!=EOF){
        for(int i = 1; i<=n; i++){
            scanf("%d",&m[i]);
            pos[m[i]] = i;//存一下当前这个数的位置
        }
        int step = 0;
        for(int i = 1; i<=n; i++){
            if(m[i] != i){
                int lt = m[i];//存一下交换之前处于i这里的数字
                step++;
                swap(m[i],m[pos[i]]);
                pos[lt] = pos[i];//更新一下交换之后的数字的位置
            }
        }
        printf("%d\n",step);
    }
    return 0;
}
/*
PutIn:
3
1 2 3
5
5 4 3 2 1
5
5 4 1 2 3
4
4 3 1 2
6
5 6 3 4 1 2
10
9 8 10 5 3 2 4 7 6 1
PutOut:
0
2
3
3
2
9
*/
View Code

 

posted @ 2018-10-26 21:35  sykline  阅读(265)  评论(0编辑  收藏  举报