jiahuimbzuai/CoQuIR huggingface dataset:
//  [javascript]
//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){  
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var s = next();
  var t = next();
  var output = 100000;
  for(var i = 0; i < s.length - t.length + 1; i++){
    var count = 0;
    for(var j = 0; j < t.length; j++){
      if(s[i + j] != t[j]){
        count++;
      }
    }
    output = Math.min(output, count);
  }
  myout(output);
}
//  [javascript]
function Main(s, t) {
  let min = 1000;
  for (let i = 0; i <= s.length - t.length; i++) {
    let change = t.length;
    for (let j = 0; j < t.length; j++) {
      if (s.charAt(i + j) == t.charAt(j)) {
        change--;
      }
    }
    if (change < min) min = change;
  }
  return min;
}

function readlines() {
  return require('fs').readFileSync('/dev/stdin', 'utf8').split('\n');
}

(async () => {
  const lines = readlines();
  console.log(await Main(lines[0], lines[1]));
})();
//  [javascript]
const main = stdin => {
  const [S, T] = stdin.trim().split('\n')
  let max = 0
  for (let i = 0; i <= S.length - T.length; i++) {
    let count = 0
    for (let j = 0; j < T.length; j++) {
      if (S[i + j] === T[j]) {
        count++
      }
    }
    max = Math.max(count, max)
  }

  console.log(T.length - max);
}

// 標準入力
main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [go]
package main

import "fmt"

func main() {
	var s, t string
	fmt.Scan(&s, &t)

	ss := split(s)
	tt := split(t)
	min := 1000

	nocut := false
	for i := 0; i < len(ss);i++ {
		cnt := len(tt)
		for j := 0; j < len(tt); j++ {
			if i+j == len(ss) {
				// if i+j >= len(ss)-1 {
				nocut = true
				break
			}

			if ss[i+j] == tt[j] {
				cnt--
			}
		}
		if nocut {
			continue

		}
		if cnt <  min {
			min = cnt
		}
	}

	fmt.Println(min)
}

func split(s string) []string {
	ret := make([]string, len([]rune(s)))
	for i, v := range []rune(s) {
		ret[i] = string(v)
	}
	return ret
}
//  [go]
package main

import "fmt"

func main() {
	var s, t string
	fmt.Scan(&s, &t)

	var max_match, temp_max_match int
	max_match = 0
	for i:=0; i <= len(s)-len(t); i++ {
		temp_max_match = 0
		for j:=0; j < len(t); j++ {
			if s[j+i] == t[j]{
				temp_max_match++
			}
		}
		if temp_max_match > max_match {
			max_match = temp_max_match
		}
	}
	fmt.Println(len(t)-max_match)
}
//  [ruby]
s = gets.chomp
t = gets.chomp

ans = 10 ** 20

m = s.size
n = t.size

(0..m-n).each do |i|
  tmp = 0
  (0..n-1).each do |j|
    if s[i..i+n-1][j] != t[j]
      tmp += 1
    end
  end
  ans = [ans, tmp].min
end
puts ans
//  [ruby]
s = gets.chomp
t = gets.chomp

array = []
(s.length - t.length + 1).times do |i|
#   puts "#{s[i..t.length - 1 + i]} #{t}"
  cnt = 0
  t.length.times do |j|
    # puts "#{s[i..t.length - 1 + i][j]} #{t[j]}"
    if s[i..t.length - 1 + i][j] != t[j]
      cnt += 1
    end
  end
  array << cnt
end

puts array.min
//  [ruby]
S = gets.chomp!
T = gets.chomp!

min_count = Float::INFINITY
(0...(S.size)).each do |i|
  count = T.size
  if S[i...(S.size)].size >= T.size
    S[i...(S.size)].split('').zip(T.split('')).each do |s, t|
      if s == t
        count -= 1
      end
    end
  end

  if min_count > count
    min_count = count
  end
end

puts min_count
//  [rust]
#![allow(unused_imports)]
#![allow(non_snake_case)]
use proconio::marker::*;
use proconio::{fastout, input};

#[fastout]
fn main() {
    input! {
        s: String,
        t: String,
    }
    let mut res = Vec::with_capacity(s.len());
    for i in 0..=s.len() - t.len() {
        let mut c = 0;
        for k in 0..t.len() {
            if s.chars().nth(i + k) != t.chars().nth(k) {
                c += 1;
            }
        }
        res.push(c);
    }
    println!("{}", res.iter().min().unwrap())
}
//  [rust]
use proconio::{input, fastout};

#[fastout]
fn main() {
    input!{
        s: String,
        t:String,
    }

    let mut min_diff = t.len();
    for i in 0..=(s.len() - t.len()) {
        let mut diff_num = 0;
        for k in 0..t.len() {
            if t.chars().nth(k) != s.chars().nth(i + k) {
                diff_num += 1;
            }
        }
        min_diff = min_diff.min(diff_num);
    }

    println!("{}", min_diff);
}
//  [rust]
use proconio::input;
use std::cmp::min;

fn main() {
    input!(s: String);
    input!(t: String);
    let mut score = t.len();
    for i in 0..(s.len() - t.len() + 1) {
        let mut tmp_score = 0;
        for j in 0..t.len() {
            if s.chars().nth(i+j) != t.chars().nth(j) {
                tmp_score += 1;
            }
        }
        score = min(score, tmp_score);
    }
    println!("{}", score)
}
//  [swift]
import Foundation

let s = readLine()!
let t = readLine()!

let minCost = (0...s.count - t.count).lazy
    .map { s.dropFirst($0) }
    .map { zip($0, t).lazy.filter { $0 != $1 }.count }
    .min()!

print(minCost)
//  [swift]
// 🐋💭
import Foundation

func readInts() -> [Int] {
    return readLine()!.split(separator: " ").map { Int($0)! }
}

func readInt() -> Int {
    return Int(readLine()!)!
}

func readDoubles () -> [Double] {
    return readLine()!.split(separator: " ").map { Double($0)! }
}

func readDouble() -> Double{
    return Double(readLine()!)!
}

func readLines() -> [String] {
    return readLine()!.map { String($0) }
}
///最大公約数を返す
func gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}

///最大公約数を返す
func gcd(_ array: [Int]) -> Int {
    var value = array[0]
    if array.count > 1 {
        for i in 1..<array.count {
            value = gcd(value, array[i])
        }
    }
    return value
}

///最小公倍数を返す
func lcm(_ m:Int, _ n:Int) -> Int {
    return m * n / gcd(m, n)
}

///素数判定(試し割り)
func isPrime(_ x:Int) -> Bool {
    if x <= 1 || x % 2 == 0 { return false }
    if x == 2 { return true }
    for i in stride(from: 3, to: Int(ceil(sqrt(Double(x)))), by: 2){
        if x % i == 0 {
            return false
        }
    }
    return true
}

//https://program-life.com/669
///実行速度の計測
func exectionTime(action: () -> Void) {
    let startDate = Date()
    action()
    let endDate = Date()
    print(endDate.timeIntervalSince(startDate))
}

//https://riptutorial.com/ja/swift/example/14738/インデックスを知らずに配列から要素を削除する
extension Array where Element: Equatable {
    
    mutating func remove(_ element: Element) {
        _ = firstIndex(of: element).flatMap {
            self.remove(at: $0)
        }
    }
}

func binarySearch(rifgt:Int, key:Int, ary:[String]) -> Int{
    var left = 0
    var right = rifgt
    
    while abs(right - left) > 1 {
        let mid = left + (right - left) / 2
        
        if Int(ary[mid])! < key {
            left = mid
            
        } else {
            right = mid
        }
    }
    return left
}

func arrangement (prev:String, ary:[String], returnVal:[String]) -> [String] {
    var returnVal = returnVal
    if ary.count == 0 {
        returnVal.append(prev)
        return returnVal
    }
    
    for s in ary {
        let wprev = prev + s
        var wary = ary
        wary.remove(s)
        returnVal = arrangement(prev: wprev, ary: wary, returnVal: returnVal)
    }
    return returnVal
}
// https://algo-logic.info/divisor/
/// 約数の配列を返す
func divisor(_ n:Int) -> [Int] {
    var ret = [Int]()
    var i = 1
    while i * i <= n {
        if n % i == 0 {
            ret.append(i)
            if i * i != n {
                ret.append(n / i)
            }
        }
        i += 1
    }
    return ret.sorted()
}

func main() {
    let S = readLines()
    let T = readLines()
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿入力
    var ans = 1000
    
    let length = S.count == T.count ? 1: S.count - T.count
    for i in 0..<length {
        var cnt = 0
        for j in 0..<T.count {
            if S[i + j] != T[j] {
                cnt += 1
            }
        }
        ans = min(ans, cnt)
    }
    print(ans)
}
main()
//  [typescript]
import { readFileSync } from 'fs'
import { reverse } from 'dns'
import { start } from 'repl'
 
let lines: string[] = [];
const reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout
});
 
reader.on('line', function (line: string) {
    lines.push(line);
});
reader.on('close', function () {
    let S = lines[0]
    let T = lines[1]
    let ans = 1000000

    for(let i = 0; i<= S.length - T.length; i++) {
        let tmp = 0
        for(let j = 0; j < T.length; j++) {
            if(S[i+j] != T[j]) tmp++
        }
        ans = Math.min(tmp, ans)
    }

    console.log(ans)
});
//  [typescript]
import * as fs from 'fs';

const input = fs.readFileSync('/dev/stdin', 'utf8');
// const input = fs.readFileSync('./input.txt', 'utf8');

_b(input);

function _b(input: string) {
  let min = 1000;

  const [S, T] = input.split('\n');

  for (let i = 0; i <= S.length - T.length; i++) {
    min = Math.min(min, distance(T, S.substr(i, T.length)));
  }

  console.log(min);
}

function distance(l: string, r: string) {
  if (l.length !== r.length) {
    throw new Error('not match ' + l.length + ' ' + r.length);
  }
  let n = 0;
  for (let i = 0; i < l.length; i++) {
    if (l[i] !== r[i]) {
      n++;
    }
  }
  return n;
}
//  [typescript]
import * as fs from 'fs';

// パラメタのセパレータ
// - 問題に合わせて変更
const sep = "\n"; 

// エントリポイント
// - OSによるパラメタの処理の違いを吸収
entrypoint(sep);
function entrypoint(sep) {
    try {
        var input = fs.readFileSync("/dev/stdin", "utf8").split(sep);
        main(input);
    }
    catch (ex) {
        const lines = [];
        const reader = require('readline').createInterface({
            input: process.stdin,
            output: process.stdout
        });
        reader.on('line', function (line) {
            lines.push(line);
        });
        reader.on('close', function () {
            if (sep == "\n") {
                input = lines;
            } else {
                input = lines[0].split(sep);
            }
            main(input);
        });
    }
}

// メイン
function main(input) {
    const s = input[0];
    const t = input[1];
    var l = t.length;
    for (var i = 0; i <= s.length - t.length; i++) {
        var l0 = 0;
        for (var j = 0; j < t.length; j++) {
            if (s[i + j] != t[j]) {
                l0++;
                if (l < l0) break;
            }
        }
        if (l0 < l) l = l0;
        if (l == 0) break;
    }
    console.log(l);
}
//  [python]
def main():
    n, *p = map(int, open(0).read().split())
    ans = 0
    i = False
    for p, q in enumerate(p, 1):
        j = p == q
        i = (i or j) and (not i)
        ans += i

    print(ans)


if __name__ == '__main__':
    main()
//  [python]
def resolve():
  n = int(input())
  p = list(map(int, input().split()))

  prev = False
  ans = 0
  for i in range(n):
    if i == p[i]-1:
      if (prev):
        prev = False
      else:
        ans += 1
        prev = True
    else:
      prev = False

  print(ans)

  return

if __name__ == "__main__":
  resolve()
//  [python]
def main():
    n, *p = map(int, open(0).read().split())
    res = []
    tmp = False
    for i, j in enumerate(p, 1):
        if i == j:
            tmp = not tmp
            res.append(tmp)
        else:
            tmp = False

    ans = sum(res)
    print(ans)


if __name__ == '__main__':
    main()
//  [python]
input()
get_data = input().split(' ')  # String
default = 1
dup_list = list()
for v in get_data:
  if int(v) == default:
    dup_list.append(int(v))
  default += 1
 
del_count = 0
next_skip = False
for v in dup_list:
  if next_skip:
    next_skip = False
    continue
  if v+1 in dup_list:
    next_skip = True
  del_count += 1
  
print(del_count)
//  [python]
N = int(input())
numbers = [int(i)-1 for i in input().split()]

need_fix_index = []

for i, v in enumerate(numbers):
    if i == v:
        need_fix_index.append(i)
        
cnt = 0

while need_fix_index:
    cnt += 1
    v = need_fix_index.pop(0)
    if len(need_fix_index) == 0:
        break
    if abs(need_fix_index[0]-v) == 1:
        del need_fix_index[0]
    
print(cnt)
//  [python]
N = int(input())
p = list(map(int, input().split()))

count = 0
now = 0
for i in range(len(p)):
    if len(p) == 0:
        break
    if now+1 == p[0]:
        p.pop(0)
        count += 1
        now += 1
    if len(p) == 0:
        break
    p.pop(0)
    now += 1
print(count)
//  [java]
import java.util.Scanner;
import java.util.stream.IntStream;

public class Main {

	public static void main(String[] args) {
		try (Scanner scanner = new Scanner(System.in)) {
			int n = scanner.nextInt();
			int[] p = new int[n];
			IntStream.range(0, n).forEach(i -> p[i] = scanner.nextInt());
			System.out.println(getResult(p, 0));
		}
	}

	/**
	 * @param p     数字の配列
	 * @param start 開始インデックス
	 * @return 最小の入替え数
	 */
	private static int getResult(int[] p, int start) {
		int next = -1;
		for (int i = start; i < p.length; i++) {
			if ((i + 1) == p[i]) {
				next = i;
				break;
			}
		}
		if (next >= 0) {
			int result = Integer.MAX_VALUE;
			if (next == p.length - 1) {
				result = getResult(swap(p, next - 1), next - 1) + 1;
			} else {
				result = getResult(swap(p, next), next) + 1;
			}
			return result;
		}
		return 0;
	}

	/**
	 * @param p     数字の配列
	 * @param index インデックス
	 * @return 数字の配列のインデックスとインデックス＋1の要素を入替えた配列
	 */
	private static int[] swap(int[] p, int index) {
		int temp = p[index];
		p[index] = p[index + 1];
		p[index + 1] = temp;
		return p;
	}
}
//  [java]

import java.util.Scanner;

/**
 *
 * @author bhatti
 */
public class Main {

    
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] p = new int[N];
        for (int i = 0; i < N; ++i) {
            p[i] = sc.nextInt();
        }
       int count = 0;

        for (int i = 0; i < N; i++) {
            if (p[i] == i + 1){
                count++;
                i++;
            }

        }
        System.out.println(count);
    }

   
}
//  [java]
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Main {

    private final static Scanner sc = new Scanner(System.in);

    /**
     * 本処理を実行します。
     */
    public static void execute() {
        int n = nextInt();
        List<Integer> p = new ArrayList<>(n);

        for (int i = 0; i < n; i++) {
            int input = nextInt();
            p.add(input);
        }

        long swapCount = 0L;

        for (int i = 0; i < n; i++) {
            int pi = p.get(i);

            if (pi == i + 1) {
                // 最後以外は右を見る
                if (i < n - 1) {
                    int piRight = p.get(i + 1);

                    // 右隣もpi = i ならそこで入れ替える
                    if (piRight == i + 1) {
                        Collections.swap(p, i, i + 1);
                    } else if (piRight == i) {
                        // 右隣が今の位置の番号なら左と入れ替える
                        Collections.swap(p, i, i - 1);
                    } else {
                        Collections.swap(p, i, i + 1);
                    }
                } else {
                    // 最後は左を見る
                    Collections.swap(p, i, i - 1);
                }

                swapCount++;
            }
        }

        out(swapCount);
    }

    /**
     * 次の標準入力をintで受け取ります。
     * @return 標準入力値(int)
     */
    public static int nextInt() {
        return sc.nextInt();
    }

    /**
     * 次の標準入力をStringで受け取ります。
     * @return 標準入力値(String)
     */
    public static String nextString() {
        return sc.next();
    }

    /**
     * 次の標準入力を指定回数分intで受け取ります。
     * @param n 取得回数
     * @return 取得した標準入力値の配列(int)
     */
    public static int[] nextInts(int n) {
        int[] arr = new int[n];

        for (int i = 0; i < n; i++) {
            arr[i] = nextInt();
        }

        return arr;
    }

    /**
     * 標準出力にオブジェクトを出力します。
     * @param o 出力対象
     */
    public static void out(Object o) {
        System.out.println(o);
    }

    public static void main(String[] args) {
        execute();
    }
}
//  [cpp]
#pragma GCC optimize ("O3")
#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
//#include<vector>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int N = getint();
	int kotae = 0;
	int mae = getint();
	int i = 1;
	for (; i < N; i++) {
		int tugi = getint();
		if (mae == i) {
			kotae++;
			mae = getint();
			i++;
		}
		else mae = tugi;
	}
	if (i == N && mae == N) kotae++;

	printf("%d", kotae);

	Would you please return 0;
}
//  [cpp]
#pragma GCC optimize ("Ofast")
#include<bits/stdc++.h>
using namespace std;
inline void rd(int &x){
  int k, m=0;
  x=0;
  for(;;){
    k = getchar_unlocked();
    if(k=='-'){
      m=1;
      break;
    }
    if('0'<=k&&k<='9'){
      x=k-'0';
      break;
    }
  }
  for(;;){
    k = getchar_unlocked();
    if(k<'0'||k>'9'){
      break;
    }
    x=x*10+k-'0';
  }
  if(m){
    x=-x;
  }
}
inline void wt_L(char a){
  putchar_unlocked(a);
}
inline void wt_L(int x){
  char f[10];
  int m=0, s=0;
  if(x<0){
    m=1;
    x=-x;
  }
  while(x){
    f[s++]=x%10;
    x/=10;
  }
  if(!s){
    f[s++]=0;
  }
  if(m){
    putchar_unlocked('-');
  }
  while(s--){
    putchar_unlocked(f[s]+'0');
  }
}
int N;
int A[100001];
int main(){
  int i, res=0;
  rd(N);
  {
    int Lj4PdHRW;
    for(Lj4PdHRW=0;Lj4PdHRW<(N);Lj4PdHRW++){
      rd(A[Lj4PdHRW]);A[Lj4PdHRW] += (-1);
    }
  }
  for(i=0;i<(N);i++){
    if(A[i]==i){
      res++;
      A[i+1] = -1;
    }
  }
  wt_L(res);
  wt_L('\n');
  return 0;
}
// cLay varsion 20190822-2

// --- original code ---
// int N, A[100001];
// {
//   int i, res = 0;
//   rd(N,(A--)(N));
//   rep(i,N){
//     if(A[i]==i) res++, A[i+1] = -1;
//   }
//   wt(res);
// }
//  [cpp]
#include <bits/stdc++.h>

using namespace std;

#define countof(a) (sizeof(a)/sizeof(*a))

#define vi vector<int>
#define vvi vector<vector<int> >
#define vpi vector<pi >
#define pi pair<int,int>
#define mp make_pair
#define fi first
#define se second
#define all(n) n.begin(), n.end()

#define FROMTO(var, from, to) for (register int var = (from), var##down = ((int)(to)) < ((int)(from));var##down ? (var >= (int)(to)) : (var <= (int)(to));var##down ? var-- : var++)
#define UPTO(var, from, to)   for (register int var = (from); var <= ((int)to); var++)
#define DOWNTO(var, from, to) for (register int var = (from); var >= ((int)to); var--)
#define FOR(var, to)          UPTO(var, 0, (to)-1)
#define DOWN(var, from)       DOWNTO(var, (from)-1, 0) 

#define INIT(var, val) FOR(i,countof(var)) var[i] = val
#define INPUT(var) FOR(i,countof(var)) cin >> var[i]
#define INPUT1(var) FOR(i,countof(var)) cin >> var[i], var[i]--

#define SORT(v) qsort(v,countof(v),sizeof(*v),int_less)
#define SORTT(v) qsort(v,countof(v),sizeof(*v),int_greater)
#define QSORT(v,b) qsort(v,countof(v),sizeof(*v),b)

#define MOD 1000000007
#define INF ((1 << 30)-1)
#define LINF ((1LL << 62)-1)

typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;
typedef int8_t s8;
typedef int16_t s16;
typedef int32_t s32;
typedef int64_t s64;

struct Comb {
    vector<vector<s64> > data;
    Comb(int n) { // O(n^2)
        data = vector<vector<s64> >(n+1,vector<s64>(n+1,1));
        UPTO(i,1,n) {
            FOR(j,i+1) {
                if (!j || j == i) data[i][j] = 1;
                else data[i][j] = data[i-1][j-1] + data[i-1][j];
            }
        }
    }
    
    s64 ncr(int n, int r) {
        return data[n][r];
    }
};

int int_less(const void *a, const void *b) {
  return (*((const int*)a) - *((const int*)b));
}
int int_greater(const void *a, const void *b) {
  return (*((const int*)b) - *((const int*)a));
}

#define mygc(c) (c)=getchar_unlocked()

int ri() {
	int c,s=0,r=0;
	for(;;){ mygc(c); if(c=='-'){s=1;break;} if(c<='9'&&c>='0'){r=c-'0';break;}}
	for(;;){ mygc(c); if(c>'9'||c<'0')break; r= r* 10 + c-'0';}
	if(s)r=-r;
	return r;
}

int main() {
    int n = ri();
	int a[n];
	FOR(i,n) a[i] = ri();
	
	int res = 0;
	FOR(i,n) {
		if (a[i] == i+1) {
			res++;
			i++;
		}
	}
	
	cout << res << endl;
    return 0;
}
//  [cpp]
#include<iostream>

using namespace std;

int n,p[100001],st[100001],c;// 0 Ok 1 NG

int swap(int a,int b){
	int mp;
	mp=a;
	a=b;
	b=mp;
	return 0;
}

int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>p[i];
		if(i==p[i]) st[i]=1;
	}
	for(int i=1;i<=n;i++){
		if(st[i]==1){
			if(i==n) c++;
			else{
				if(st[i+1]==1){
					st[i]=0;
					st[i+1]=0;
					i=1;
					c++;
				}
				else{
					st[i]=0;
					i=1;
					c++;
				}
			}
		}
	}
	cout<<c<<endl;
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
int main(){
	int n,p[100000];
	cin>>n;
	for(int i=0;i<n;i++){
		cin>>p[i];
	}
	int ans=0;
	for(int i=0;i<n;i++){
		if(p[i]==i+1){
			swap(p[i],p[i+1]);
			ans++;
			i=-1;
		}
	}
	cout<<ans<<endl;
}
//  [cpp]
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
#include <functional>
#include <map>
#include <iomanip>

using namespace std;

int main() {
	int i, j, N, tmp, cnt=0;
	int p[100001] = { 0 };
	int pp[100001] = { 0 };

	cin >> N;
	for (i = 0; i < N; i++) {
		cin >> p[i];
	}

	int flag;
	for (; ; ) {
		flag = 0;
		for (i = 1; i <= N; i++) {
			if (i == p[i-1]) {
				tmp = p[i-1];
				p[i-1] = p[i ];
				p[i ] = tmp;
				cnt++;
				flag = 1;
				break;
			}

		}
		if (flag == 0) {
			break;
		}


	}


	//cout << "cnt->" << cnt << endl;
	cout  << cnt << endl;




	return 0;
}
//  [c]
s;
main()
{
  int N;scanf("%d",&N);
  int i=1;
  while(i<=N)
  {
    int a;scanf("%d",&a);
    if(a==i)
    {
      s++;
      scanf("%d",&a);
      i++;
    }
    i++;
  }
  printf("%d\n",s);
}
//  [c]
#include <stdio.h>
static int n, p, i, sum;
int main(void) {
    scanf("%d", &n);
    for (i = 1; i <= n; ++i) {
        scanf("%d", &p);
        if (p == i) {
            ++sum;
            ++i;
            scanf("%*d");
        }
    }
    printf("%d\n", sum);
    return 0;
}
//  [c]
#include <limits.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

// 内部変数 - テスト用
#ifdef D_TEST
	static int siRes;
	static FILE *szpFpT, *szpFpA;
#endif

// 実行メイン
int
fMain(
	int piTNo					// <I> テスト番号 1～
)
{
	int i;
	char lc1Buf[1024], lc1Out[1024];

	// テストファイルオープン
#ifdef D_TEST
	sprintf(lc1Buf, ".\\Test\\T%d.txt", piTNo);
	szpFpT = fopen(lc1Buf, "r");
	sprintf(lc1Buf, ".\\Test\\A%d.txt", piTNo);
	szpFpA = fopen(lc1Buf, "r");
	siRes = 0;
#endif

	// 配列数取得
	int liACnt;
#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpT);
#else
	fgets(lc1Buf, sizeof(lc1Buf), stdin);
#endif
	sscanf(lc1Buf, "%d", &liACnt);

	// 交換回数取得
	int liCnt = 0;
	int liSame = 0;
	for (i = 1; i <= liACnt; i++) {
		int liVal;
#ifdef D_TEST
		fscanf(szpFpT, "%d", &liVal);
#else
		fscanf(stdin, "%d", &liVal);
#endif

		// 一致チェック
		if (i == liVal) {			// 一致
			if (liSame == 0) {			// １回目
				liSame++;
			}
			else {						// ２回目
				liCnt++;					// 交換
				liSame = 0;
			}
		}
		else {						// 不一致
			if (liSame == 1) {			// 前回一致あり
				liCnt++;					// 交換
				liSame = 0;
			}
		}
	}
#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpT);
#else
	fgets(lc1Buf, sizeof(lc1Buf), stdin);
#endif
	if (liSame == 1) {			// 前回一致あり
		liCnt++;					// 交換
		liSame = 0;
	}

	// 結果セット
	sprintf(lc1Out, "%d\n", liCnt);

	// 結果表示
#ifdef D_TEST
	fgets(lc1Buf, sizeof(lc1Buf), szpFpA);
	if (strcmp(lc1Buf, lc1Out)) {
		siRes = -1;
	}
#else
	printf("%s", lc1Out);
#endif

	// テストファイルクローズ
#ifdef D_TEST
	fclose(szpFpT);
	fclose(szpFpA);
#endif

	// テスト結果
#ifdef D_TEST
	if (siRes == 0) {
		printf("OK %d\n", piTNo);
	}
	else {
		printf("NG %d\n", piTNo);
	}
#endif

	return 0;
}

int
main()
{

#ifdef D_TEST
	int i;
	for (i = D_TEST_SNO; i <= D_TEST_ENO; i++) {
		fMain(i);
	}
#else
	fMain(0);
#endif

	return 0;
}
//  [c]
#include <stdio.h>

#define N_MAX 100000

int parse(char *text);

int main(void)
{
	int n, i, p_idx, count;
	int perm[N_MAX+1];
	char buf[7];

	scanf("%d%*c", &n);

	i = 0;
	p_idx = 1;
	while(1) {
		int flag = 0;
		scanf("%c", &buf[i]);
		if(buf[i] == ' ' || buf[i] == '\n') {
			if(buf[i] == '\n') flag = 1;
			buf[i] = '\0';
			perm[p_idx++] = parse(buf);
			//printf("%d,%d\n", p_idx-1, perm[p_idx-1]);
			if(flag) break;
			i = 0;
			continue;
		}
		i++;
	}

	count = 0;
	for(i=1;i<n;i++) {
		if(i == perm[i]) {
			count++;
			if(i+1 == perm[i+1]) {
				i++;
			}
		}
	}

	if(i == perm[i]) count++;

	printf("%d\n", count);
	
	return 0;
}

int parse(char *text)
{
	int i, ret, len;

	i = 0;
	while(1) {
		if(text[i] == '\0') {
			len = i;
			break;
		}
		i++;
	}

	ret = 0;
	for(i=len-1;i>=0;i--) {
		int a = 1, j;
		for(j=0;j<len-i-1;j++) a *= 10;
		ret += (int)(text[i] - '0') * a;
	}

	return ret;
}
//  [c]
#include<stdio.h>
int main(){
  int n,i;
  scanf("%d",&n);
  int p[n+1];
  for(i=1;i<=n;i++)
    scanf("%d",&p[i]);
  int min=0;
  for(i=1;i<n;i++){
    if(p[i]==i){
      p[i]=p[i+1];
      p[i+1]=i;
      min++;
    }
  }
  if(p[n]==n)
    min++;
  printf("%d\n",min);
  return 0;
}
//  [javascript]
function Main(input) {
  input = input.split("\n");
  var n = parseInt(input[0].split(" ")[0]);
  tmp = input[1].split(" ");
  p = new Array(n).fill(0);
  for(i=0;i<n;i++){
    p[i]=parseInt(tmp[i]);
  }
  var ans=0;
  for(i=0;i<n;i++){
    if(p[i]==i+1&&i!=n-1){
      var x=p[i];
      p[i]=p[i+1];
      p[i+1]=x;
      ans++;
    }else if(p[i]==i+1){
      ans++;
    }
  }

  console.log('%s', ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf8');

var g_input = '';
process.stdin.on('data', function(chunk) {
    g_input += chunk;
});

process.stdin.on('end', function() {
    Main(g_input.split(/\r?\n/));
});

function Main(input) {
    var n = parseInt(input[0], 10);
    var values = input[1].split(' ');
    var p = new Array(n);
    for (var i = 0; i < n; i++) {
        p[i] = parseInt(values[i], 10);
    }

    var swapCount = 0;
    for (var i = 0; i < n; i++) {
        if (p[i] == i + 1) {
            if (i == n - 1) {
                swap(p, i, i - 1);
                swapCount++;
            }
            else {
                swap(p, i, i + 1);
                swapCount++;
            }
        }
    }

    console.log(swapCount);
}

function swap(array, src, dest) {
    var temp = array[src];
    array[src] = array[dest];
    array[dest] = temp;
}
//  [javascript]
module.exports=function(e){var t={};function r(n){if(t[n])return t[n].exports;var o=t[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=e,r.c=t,r.d=function(e,t,n){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)r.d(n,o,function(t){return e[t]}.bind(null,o));return n},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="",r(r.s=0)}([function(e,t,r){r(1)(r(2).readFileSync("/dev/stdin","UTF-8"))},function(e,t){e.exports=function(e){for(var t=e.split("\n"),r=Number(t[0]),n=t[1].split(" ").map(function(e){return Number(e)}),o=0,u=0,i=0;i<r;i++)n[i]-1==i?1==u?u=0:(o+=1,u=1):u=0;console.log(o)}},function(e,t){e.exports=require("fs")}]);
//  [javascript]
function myin(){return require("fs").readFileSync("/dev/stdin", "utf8").trim();}
function myout(t){console.log(t);}//standard output
function myerr(t){console.error(t);}//standard error
//[no]param
//0:何もしない  1:数値へ変換  2:半角SPで分割  3:改行で分割  4:半角SPで分割し、数値配列へ
//5:改行で分割し、数値配列へ  6:1文字に分割  7:1文字に分割し、数値配列へ
function myconv(i,no){switch(no){case 0:return i;case 1:return parseInt(i);case 2:return i.split(" ");case 3:return i.split("\n");case 4:return i.split(" ").map((a)=>Number(a));case 5:return i.split("\n").map((a)=>Number(a));case 6:return i.split("");case 7:return i.split("").map((a)=>Number(a));}}
function Main(input) {
  input = myconv(input,3);
  var N = myconv(input[0],1);
  var list = myconv(input[1],4);
  var eqlist = new Array(N).fill(0);
  for(var i = 0; i < N; i++){
    if(list[i] == i+1){
       eqlist[i] = 1;
    }
  }
  myerr(eqlist);
  var ruiseki = 0;
  var output = 0;
  for(var i = 0; i < N; i++){
    if(eqlist[i] == 1){
       ruiseki++;
    }else{
       output += Math.ceil(ruiseki / 2);
       ruiseki = 0;
    }
  }
  output += Math.ceil(ruiseki / 2);
  myout(output);
}
Main(myin());
//  [javascript]
"use strict";
    
const main = arg => {
    arg = arg.trim().split("\n");
    const N = parseInt(arg[0]);
    const P = arg[1].split(" ").map(n=>parseInt(n));
    
    let answer = 0;
    
    for(let i in P) {
        if(parseInt(i) + 1 === P[i]) {
            let temp = P[i];
            P[i] = P[parseInt(i) + 1];
            P[parseInt(i) + 1] = temp;
            answer++;
        }
    }
    
    console.log(answer);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [javascript]
"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let n = nextInt()
    let p = nextIntArray()
    let cnt = 0
    for(let i = 0; i<p.length; i++){
        if(p[i] == i+1){
            if(i != n){
                let tmp = p[i+1]
                p[i+1] = p[i]
                p[i] = tmp
            }
            cnt++
        }
    }
    console.log(cnt)
}
Main()
//  [go]
package main

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
)

func getScanner(fp *os.File) *bufio.Scanner {
	scanner := bufio.NewScanner(fp)
	scanner.Split(bufio.ScanWords)
	scanner.Buffer(make([]byte, 500001), 500000)
	return scanner
}

func getNextString(scanner *bufio.Scanner) string {
	scanner.Scan()
	return scanner.Text()
}

func getNextInt(scanner *bufio.Scanner) int {
	i, _ := strconv.Atoi(getNextString(scanner))
	return i
}

func getNextInt64(scanner *bufio.Scanner) int64 {
	i, _ := strconv.ParseInt(getNextString(scanner), 10, 64)
	return i
}

var abc [200][200]int

func main() {
	fp := os.Stdin
	if len(os.Args) > 1 {
		fp, _ = os.Open(os.Args[1])
	}

	scanner := getScanner(fp)
	writer := bufio.NewWriter(os.Stdout)

	n := getNextInt(scanner)

	ans := 0
	d := 0

	for i := 0; i < n; i++ {
		p := getNextInt(scanner) - 1
		if p == i {
			d++
			continue
		}
		ans += (d + 1) / 2
		d = 0
	}
	ans += (d + 1) / 2
	fmt.Fprintln(writer, ans)

	writer.Flush()
}
//  [go]
// ProblemURL : https://atcoder.jp/contests/abc072/tasks/arc082_b
// ---------------------------------------------
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	ps := make([]int, n)
	for i := range ps {
		fmt.Scan(&ps[i])
		ps[i]--
	}

	as := make([]int, 0, n)
	for i := range ps {
		if i == ps[i] {
			as = append(as, i)
		}
	}

	ct := 0
	for i := 0; i < len(as); i++ {
		if i+1 < len(as) && as[i]+1 == as[i+1] {
			i++
			ct++
		} else {
			ct++
		}
	}
	fmt.Println(ct)
}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	count := 0
	flg := false
	for i := 1; i < n + 1; i++ {
		var tmp int
		fmt.Scan(&tmp)
		if flg && i == tmp {
			flg = false
		} else if i == tmp {
			count++
			flg = true
		} else {
			flg = false
		}
	}
	fmt.Println(count)
}
//  [go]
// Package main provides
//
// File:  d.go
// Author: ymiyamoto
//
// Created on Wed Jan  9 00:36:47 2019
//
package main

import "fmt"

func scanSlice(slice []int) {
	for i := range slice {
		fmt.Scan(&slice[i])
	}
}

func main() {
	var N int
	fmt.Scan(&N)
	arr := make([]int, N)
	scanSlice(arr)

	ans := 0
	for i := range arr {
		if i < len(arr)-1 {
			if arr[i] == i+1 {
				arr[i], arr[i+1] = arr[i+1], arr[i]
				ans++
			}
		} else {
			if arr[i] == i+1 {
				arr[i], arr[i-1] = arr[i-1], arr[i]
				ans++
			}
		}
	}
	fmt.Println(ans)
}
//  [ruby]
n = gets.to_i
pp = gets.split.map(&:to_i)

ans = 0
i = 0
while i < n
    if pp[i] == i + 1
        i += 1
        ans += 1
    end
    i += 1
end

puts ans
//  [ruby]
n = gets.to_i
arr = gets.split.map(&:to_i)

i = 0
ans = 0
while i < n do
    if i + 1 == arr[i]
        ans += 1
        i += 2
    else
        i += 1
    end
end

puts ans
//  [ruby]
n = gets.to_i
p = gets.split.map(&:to_i)
p << 0
cnt = 0
i = 0
while i <= n
  if i + 1 == p[i]
    cnt += 1
    i += 1
  end
  i += 1
end
puts cnt
//  [ruby]
N = gets.to_i
PS = gets.chomp.split.map(&:to_i)

MAX = 10**5 + 1
m = Array.new(MAX, false)

count = 0
10.times do
  PS.each_with_index do |p, i|
    m[i] = p if p == i+1
  end
  MAX.times do |i|
    next unless m[i]
    if PS[i+1] != i && m[i] != i+2
      PS[i+1], PS[i] = PS[i], PS[i+1]
      count += 1
      m[i] = false
      m[i+1] = false
    elsif PS[i-1] != i && m[i] != i
      PS[i-1], PS[i] = PS[i], PS[i-1]
      count += 1
      m[i] = false
      m[i-1] = false
    end
  end
end

p count
//  [ruby]
n,*ps=$<.read.split.map(&:to_i)

ret = ps.map.with_index {|n,i| n == i+1}.
  slice_when{|a,b| a != b}.
  select{|a|a[0]}.
  map{|a|(a.length+1)/2}.
  inject(&:+) || 0
p ret
//  [ruby]
n = gets.to_i
p = gets.chomp.split(" ").map(&:to_i)
cnt = 0
n.times do |i|
  if p[i] == i+1
    if i == n-1
      cnt += 1
    else
      if p[i+1] == i+2
        cnt += 1
        p[i],p[i+1] = p[i+1],[i]
      else
        cnt += 1
      end
    end
  end
end
puts cnt
//  [rust]
#[macro_use]
mod input {

use std;
use std::io;

const SPLIT_DELIMITER: char = ' ';

#[macro_export]
#[allow(unused_macros)]
macro_rules! input {
    ( $($x:expr ),*) => {
        {
            let temp_str = input_line_str();
            let mut split_result_iter = temp_str.split_whitespace();
                $(
                let buf_split_result = split_result_iter.next();
                let buf_split_result = buf_split_result.unwrap();
                    ($x) = buf_split_result.parse().unwrap();
                )*
        }
    };
}

#[allow(dead_code)]
pub fn input_line_str() -> String {
    let mut s = String::new();
    io::stdin().read_line(&mut s).unwrap();
    s.trim().to_string()
}

#[allow(dead_code)]
pub fn p<T>(t: T)
where
    T: std::fmt::Display,
{
    println!("{}", t);
}

#[allow(dead_code)]
pub fn input_vector2d<T>(line: usize) -> Vec<Vec<T>>
where
    T: std::str::FromStr,
{
    let mut v: Vec<Vec<T>> = Vec::new();

    for _ in 0..line {
        let vec_line = input_vector();
        v.push(vec_line);
    }
    v
}

#[allow(dead_code)]
pub fn input_vector<T>() -> Vec<T>
where
    T: std::str::FromStr,
{
    let mut v: Vec<T> = Vec::new();

    let s = input_line_str();
    let split_result = s.split(SPLIT_DELIMITER);
    for z in split_result {
        let buf = match z.parse() {
            Ok(r) => r,
            Err(_) => panic!("Parse Error"),
        };
        v.push(buf);
    }
    v
}

#[allow(dead_code)]
pub fn str2vec(s: &str) -> Vec<char> {
    let mut v: Vec<char> = Vec::new();
    for c in s.chars() {
        v.push(c);
    }
    v
}

}

#[allow(unused_imports)]
use input::*;

fn main() {
    let n: usize;
    input!(n);
    let mut v = input_vector::<usize>();
    let mut i = 1;
    let mut ans = 0;
    while i < n {
        if v[i - 1] == i {
            v.swap(i - 1, i);
            ans += 1;
        }
        i += 1;
    }
    if v[n - 1] == n {
        ans += 1;
    }

    p(ans);
}
//  [rust]
fn main() {
    let n = read::<usize>();
    let ps = read_vec::<u32>();
    let mut qs = vec![false; ps.len()];

    for (i, &p) in ps.iter().enumerate() {
        if i + 1 == p as usize {
            qs[i] = true;
        }
    }

    let mut count = 0;
    let mut i = 0;
    let len = qs.len();
    while i < len {
        if i < len - 1 {
            if qs[i] && qs[i + 1] {
                count += 1;
                i += 2;
            } else if qs[i] && !qs[i + 1] {
                count += 1;
                i += 2;
            } else {
                i += 1;
            }
        } else {
            if qs[i] {
                count += 1;
            }
            i += 1;
        }
    }

    println!("{}", count);
}

#[allow(dead_code)]
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}
#[allow(dead_code)]
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>()
        .split_whitespace()
        .map(|e| e.parse().ok().unwrap())
        .collect()
}
#[allow(dead_code)]
fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}
#[allow(dead_code)]
fn yn(result: bool) {
    if result {
        println!("Yes");
    } else {
        println!("No");
    }
}
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        let s = {
            use std::io::Read;
            let mut s = String::new();
            std::io::stdin().read_to_string(&mut s).unwrap();
            s
        };
        let mut iter = s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
}

macro_rules! input_inner {
    ($iter:expr) => {};
    ($iter:expr, ) => {};
    ($iter:expr, $var:ident : $t:tt $($r:tt)*) => {
        let $var = read_value!($iter, $t);
        input_inner!{$iter $($r)*}
    };
}

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: usize,
        pp: [usize;n]
    }
    let mut pp = pp;
    let mut cnt = 0;
    for i in 0..n {
        if i+1 == pp[i] {
            if i < n-1 {
                pp.swap(i,i+1);
            }
            cnt += 1;
        }
    }
    println!("{}", cnt);
}
//  [rust]
use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;
use std::mem::swap;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
    }
}

#[fastout]
fn main() {
    input!{
        n: usize,
        mut p: [usize;n],
    }

    p.push(0);
    let mut cnt = 0;
    let mut flag: Vec<bool> = vec![true;n+1];
    for i in 0..n+1 {
        if p[i]==i+1 {
            flag[i] = false;
        }
    }
    debug!(flag);
    debug!(p.len());
    for i in 0..n {
        if flag[i]==false {
            p.swap(i,i+1);
            cnt += 1;
            debug!(i);
            if p[i+1]==i+2 {
                flag[i+1] = false;
            } else {
                flag[i+1] = true;
            }
        } 
    }
    debug!(flag);
    debug!(p);
    println!("{}", cnt);
}
//  [rust]
#![allow(non_snake_case)]

use std::io::{stdin, Read};
use std::str::FromStr;
fn read_option<T: FromStr>() -> Option<T> {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok()
}
fn read<T: FromStr>() -> T {
    let opt = read_option();
    opt.expect("failed to parse token")
}

fn main() {
    let n: usize = read();
    let mut vec: Vec<usize> = (0..n).map(|_| read()).collect();
    let mut ans = 0;
    for index in 0..n {
        let i = index + 1;
        if vec[index] == i {
            ans += 1;
            if index == n - 1 {
                vec.swap(n - 1, n - 2);
                continue;
            }
            vec.swap(index, index + 1);
        }
    }
    println!("{}", ans)
}
//  [rust]
use std::io::*;
use std::str::FromStr;

fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("filed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n:usize = read();
    let mut v:Vec<usize> = (0..n).map(|_| read()).collect();
    let mut cnt = 0;
    for i in 0..n-1 {
        if v[i] == i+1 {
            v.swap(i, i+1);
            cnt += 1;
        }
    }
    if v[n-1] == n {
        cnt += 1;
    }
    println!("{}", cnt);
}
//  [swift]
_ = readLine()!
var ps = readLine()!.split(separator: " ").compactMap { Int($0) }

var operationCount = 0

for i in 0..<ps.count {
    if i + 1 == ps[i] {
        operationCount += 1
        if i + 1 < ps.count {
            ps.swapAt(i, i + 1)
        }
    }
}

print(operationCount)
//  [typescript]
"use strict";

main(require("fs").readFileSync("/dev/stdin", "utf8"));

function main(input) {
  const [[numsCount], nums] = input.split("\n").map(s => s.split(" ").map(Number));

  let count = 0;

  let i = 0;
  while (i <= numsCount) {
    if (nums[i] === i + 1) {
      count++;
      if(nums[i + 1] === i + 2) {
        i++;
      }
    }
    i++;
  }

  const ans = count;
  console.log(ans);
}
//  [python]
N, Q = map(int, input().split())
S = list(input())

countlist = [0 for i in range(N)]
for i in range(1, N):
    #print(S[i - 1:i + 1])
    countlist[i] = countlist[i - 1]
    if S[i - 1:i + 1] == ["A", "C"]:
        countlist[i] += 1

#print(countlist)
for i in range(Q):
    #print(i)
    l, r = map(int, input().split())
    l -= 1
    r -= 1
    ans = countlist[r] - countlist[l - 1]
    if S[l] == "C" and S[l - 1] == "A":
        #print(S[r], r)
        #print(100)
        ans -= 1
    if l == 0:
        ans = countlist[r]
    print(ans)
#print(countlist)
//  [python]
N, Q = [int(i) for i in input().split()]
S = input()
dp = [0] * N
for i in range(1, N):
    if S[i-1:i+1] == 'AC':
        dp[i] = dp[i - 1] + 1
    else:
        dp[i] = dp[i - 1]
for _ in range(Q):
    l, r = [int(i) - 1 for i in input().split()]
    print(dp[r] - dp[l])
//  [python]
N,Q=map(int,input().split())
S=input()
t = [0]*(N+1)
for i in range(len(S)-1):
    if S[i] == 'A' and S[i+1] == 'C':
        t[i+1] = 1

import numpy
res = numpy.cumsum(t)

for _ in range(Q):
    l=list(map(int,input().split()))
    print(res[l[1]-1]-res[l[0]-1])
//  [java]
import java.util.*;
public class Main{
	public static void main(String arg[]){
		Scanner sc=new Scanner(System.in);
		int a=sc.nextInt();
		int b=sc.nextInt();
		String s=sc.next();
		int arr[]=new int[a+1];
		arr[1]=0;
		for(int i=1;i<a;i++){
		if(s.charAt(i-1)=='A'&&s.charAt(i)=='C')
			arr[i+1]=1;
		}
		for(int i=1;i<=a;i++)
			arr[i]=arr[i-1]+arr[i];
		for(int i=0;i<b;i++){
			int sum=0;
			int m=sc.nextInt();
			int n=sc.nextInt();
			sum=arr[n]-arr[m];
			System.out.println(sum);
		}
	}
}
//  [java]
import java.util.*;

public class Main {
public static void main(String[] args) {
		
		Scanner keyboard = new Scanner(System.in); 
		
		int L = keyboard.nextInt();
		int Q = keyboard.nextInt();
		String N = keyboard.next();
		
		String[]moji = N.split("");
		int[]wa = new int[L+1];
		
		for(int i = 0; i<L-1; i++) {
			if(moji[i].equals("A")) {
				if(moji[i+1].equals("C")) {
					wa[i+2] = 1;
				}
			}
		}
		
		for(int j = 1; j<L+1; j++) {
			wa[j] = wa[j] + wa[j-1];
		}
		
		for(int k = 0; k<Q; k++) {
			int a = keyboard.nextInt();
			int b = keyboard.nextInt();
			if(a != 1 && moji[a-1].equals("C") && moji[a-2].equals("A")) {
				System.out.println(wa[b]- wa[a-1]-1);
			}else{
				System.out.println(wa[b]- wa[a-1]);
			}
		}
		keyboard.close();	
	}
}
//  [java]
import java.util.Scanner;
import java.util.Random;;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        int N = scan.nextInt();
        int Q = scan.nextInt();
        String S = scan.next();
        int A[] = new int[N+1];

        for(int i = 0; i < N-1; i++){
            if(S.charAt(i) == 'A' && S.charAt(i + 1) == 'C'){
                A[i+2] += 1;
            }
        }

        for(int i = 1; i < N; i++){
            A[i+1] += A[i];
        }
        A[0] = 0;

        for(int i = 0; i < Q; i++){
            int l = scan.nextInt();
            int r = scan.nextInt();
            System.out.println(A[r]-A[l]);
        }
    }
}
//  [cpp]
#include <iostream>
#include <vector>
using namespace std;


int main() {
	
	vector <int> v={};
	unsigned int N, Q, l,r, contador=0;
	string adn;
	
	cin>>N;
	cin>>Q;
	cin>>adn;
	
	for (int i=0;i<adn.size()-1;i++)
		{
			if(adn[i]=='A' )
			{
				if (adn[i+1]=='C')
				{
					v.push_back(i+1);
					
				}
			}
		}
	
	for (int m=0; m<Q;m++)
	{
		cin>>l;
		cin>>r;

		
		for (int i=0; i<v.size();i++)
		{
			
			if (l<=v[i] && v[i]<r)
			contador++;
		}
		
		cout<<contador<<endl;
		contador=0;
		
	}
	
	
	return 0;
}
//  [cpp]
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <iomanip>

using namespace std;

char s[100005];
int f[100005];

int main()
{
   // string s;
    int N,Q,cnt=0;
    cin >> N >> Q;
    cin >> s;
    for(int i=0;i<N;i++){
        if(i!=N-1&&s[i]=='A'&&s[i+1]=='C'){
            f[i]=++cnt;
            i++;
        }
    }
  //  for(int i=0;i<N;i++)
  //      printf("%d,",f[i]);
  //  cout << "\n";
    while(Q--){
        int l,r;
        cin >> l >> r;
        while(f[l-1]==0&&l-1<r-2){
            l++;
        }
        while(f[r-2]==0&&r-2>l-1)
            r--;
        if(f[r-2]==0&&f[l-1]==0)
            cout << "0\n";
        else
            cout << f[r-2]-f[l-1]+1 <<endl;

    }


    return 0;
}