AtCoder Regular Contest 082 D Derangement

AtCoder Regular Contest 082 D Derangement

与下标相同与下个交换就好了。。。。

Define a sequence of ’o’ and ’x’ of length N as follows: if pi ̸= i, the i-th symbol is ’o’, otherwise the i-th symbol is ’x’. Our objective is to change this sequence to ’ooo...ooo’.
• If there is a part ”ox” (or ”xo”) in the sequence, we can change it to ”oo” by swapping these two elements. (∵ If pi = x(x ̸= i) and pi+1 = i + 1 in the initial sequence, after the swap, both pi = i + 1 and pi+1 = x will be ’o’.) • If there is a part ”xx” in the sequence, we can change it to ”oo” by swapping these two elements. (∵ If pi = i(x ̸= i) and pi+1 = i + 1 in the initial sequence, after the swap, both pi = i + 1 and pi+1 = i will be ’o’.)
Thus, we should check the sequence from left to right, and if we find an ’x’ at the i-th position, we should swap i and i + 1 (unless i = N, in this case we should swap i and i−1).

 

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int N=1e5+10;
 7 int a[N];
 8 
 9 int main()
10 {
11     int n;
12     while(cin>>n)
13     {
14         for(int i=1;i<=n;i++) cin>>a[i];
15         int cnt=0;
16         for(int i=1;i<=n;i++){
17             if(a[i]==i){
18                 cnt++;
19                 swap(a[i],a[i+1]);
20             }
21         }
22         cout<<cnt<<endl;
23     }
24     return 0;
25 }

 

posted @ 2017-09-02 22:03  ╰追憶似水年華ぃ╮  阅读(159)  评论(0编辑  收藏  举报