jiahuimbzuai/CoQuIR huggingface dataset:
//  [go]
package main

import "fmt"

var (
	finv, inv, fac [MAX]int
)

func COM(n, k int) int {
	if n < k {
		return 0
	}
	if n < 0 || k < 0 {
		return 0
	}
	return fac[n] * (finv[k] * finv[n-k] % MOD) % MOD
}

func init() {
	fac[0] = 1
	fac[1] = 1
	finv[0] = 1
	finv[1] = 1
	inv[1] = 1
	for i := 2; i < MAX; i++ {
		fac[i] = fac[i-1] * i % MOD
		inv[i] = MOD - inv[MOD%i]*(MOD/i)%MOD
		finv[i] = finv[i-1] * inv[i] % MOD
	}
}

const (
	MOD = 1000000007
	MAX = 510000
)

func ModAdd(a, b int64) int64 {
	return (a + b) % MOD
}

func ModMul(a, b int64) int64 {
	return a * b % MOD
}

func ModSub(a, b int64) int64 {
	r := (a%MOD - b%MOD) % MOD
	if r < 0 {
		r += MOD
	}
	return r
}

func ModDiv(a, b int64) int64 {
	return a % MOD * ModInv(b) % MOD
}

func ModPow(a, n int64) int64 {
	var r int64 = 1
	for n > 0 {
		if n&1 == 1 {
			r = r * a % MOD
		}
		a = a * a % MOD
		n >>= 1
	}
	return r
}

func ModInv(a int64) int64 {
	var b, u, v int64 = MOD, 1, 0
	for b > 0 {
		t := a / b
		a -= t * b
		a, b = b, a
		u -= t * v
		u, v = v, u
	}
	u %= MOD
	if u < 0 {
		u += MOD
	}
	return u
}

type Q struct {
	idx, value int
	a, b       int
	index      int
}

type QS []*Q

func (p QS) Len() int           { return len(p) }
func (p QS) Less(i, j int) bool { return p[i].value > p[j].value }
func (pq QS) Swap(i, j int) {
	pq[i], pq[j] = pq[j], pq[i]
	pq[i].index = i
	pq[j].index = j
}

func (pq *QS) Push(x interface{}) {
	n := len(*pq)
	item := x.(*Q)
	item.index = n
	*pq = append(*pq, item)
}

func (pq *QS) Pop() interface{} {
	old := *pq
	n := len(old)
	item := old[n-1]
	old[n-1] = nil  // avoid memory leak
	item.index = -1 // for safety
	*pq = old[0 : n-1]
	return item
}

func FactoredPrimeNumber(num int) map[int]int {
	m := map[int]int{}
	return factor(m, num, 2)
}

func factor(result map[int]int, num, pnum int) map[int]int {
	if pnum*pnum > num {
		if num != 1 {
			result[num] += 1
		}
		return result
	}

	if num%pnum == 0 {
		num /= pnum
		result[pnum]++
	} else {
		pnum++
	}
	return factor(result, num, pnum)
}

func GCD(a, b int) int {
	if b == 0 {
		return a
	}
	return GCD(b, a%b)
}

func LCM(a, b int) int {
	return a * b / GCD(a, b)
}

type Po struct {
	i       int
	cnt     int
	counter int
}

func main() {
	var S string
	fmt.Scan(&S)
	last := ""
	ok := true
	for _, rs := range []rune(S) {
		if string(rs) == last {
			ok = false
			break
		}
		last = string(rs)
	}
	if ok {
		fmt.Println("Good")

	} else {
		fmt.Println("Bad")

	}
}

func Reverse(runes []rune) []rune {
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return runes
}
//  [go]
package main

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

var sc = bufio.NewReaderSize(os.Stdin, 1024*1024*10)

func main() {
	S := getStdin()
	var ch byte
	for i := 0; i < len(S); i++ {
		if ch == S[i] {
			fmt.Printf("Bad\n")
			return
		}
		ch = S[i]
	}
	fmt.Printf("Good\n")
}

func getStdin() string {
	return readLine()
}
func getStdinInt() int {
	str := getStdin()
	rtn, _ := strconv.Atoi(str)
	return rtn
}
func getStdinInt64() int64 {
	str := getStdin()
	rtn, _ := strconv.ParseInt(str, 10, 64)
	return rtn
}
func getStdinIntArr() []int {
	str := getStdin()
	list := strings.Split(str, " ")
	rtn := make([]int, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.Atoi(val)
	}
	return rtn
}

func getStdinArr() []string {
	str := getStdin()
	list := strings.Split(str, " ")
	return list
}

func getStdinIntArr64() []int64 {
	str := getStdin()
	list := strings.Split(str, " ")
	rtn := make([]int64, len(list))
	for idx, val := range list {
		rtn[idx], _ = strconv.ParseInt(val, 10, 64)
	}
	return rtn
}

func readLine() string {
	buf := make([]byte, 0, 0)
	for {
		l, p, e := sc.ReadLine()
		if e != nil {
			panic(e)
		}
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}
//  [go]
package main

import (
	"fmt"
)

func main() {

	var S string
	fmt.Scanf("%s", &S)

	if S[0] != S[1] && S[1] != S[2] && S[2] != S[3] {
		fmt.Println("Good")
	} else {
		fmt.Println("Bad")
	}

}
//  [ruby]
puts`dd`[/(.)\1/]?:Bad: :Good
//  [ruby]
#!/usr/bin/env ruby

require 'set'

class Hash
  def push(key, value)
    self[key] = [] if self[key] == nil
    self[key].push(value)
  end
end

class Array
  def lower_bound(value)
    left = -1;
    right = self.length;
    while left + 1 < right
      mid = left + (right - left) / 2;
      if self[mid] >= value
        right = mid
      else
        left = mid
      end
    end
    right
  end

  def unique
    res = [self.first]
    each_cons(2) do |a, b|
      if a != b
        res.push(b)
      end
    end
    res
  end
end

def get_ints
  gets.chomp.split.map(&:to_i)
end

def get_ints_minus_one
  get_ints.map { |x| x - 1 }
end

def get_int
  gets.chomp.to_i
end

S = gets.chomp

good = true
S.split('').each_cons(2) do |a, b|
  good = false if a == b
end

puts good ? 'Good' : 'Bad'
//  [ruby]
s = gets.chomp

p = ''
s.split("").each do |i|
  if p == i
    print "Bad\n"
    exit
  end
  p = i
end
print "Good\n"
//  [rust]
use std::io::Read;

fn main() {
    let mut s = String::new();
    let mut prev = 'a';
    std::io::stdin().read_line(&mut s);
    for c in s.chars() {
        if prev == c {
            println!("Bad");
           std::process::exit(0);
        }
        prev = c;
    }
    println!("Good");
}
//  [rust]
#![allow(unused_imports)]

use proconio::{input, fastout};
use proconio::marker::*;
use std::cmp::{max, min};

#[fastout]
fn main() {
    input! {
    s: Chars
    }
    for i in 0..s.len() -1 {
        if s[i] == s[i + 1]{
            println!("Bad");
            return
        }
    }
    println!("Good");
}
//  [rust]
fn main() {
  proconio::input!{
    mut s: proconio::marker::Chars,
  }
  let n = s.len();
  s.dedup();
  if s.len() < n { println!("Bad") }
  else { println!("Good") }
}
//  [swift]
let S = readLine()!.characters.map{String($0)}
var ans = "Good"
for i in 1..<4 {
    if S[i] == S[i-1] {
        ans = "Bad"
        break
    }
}
print(ans)
//  [swift]
let arr=Array(readLine()!.characters)

var i = 0; var j = 0; var o = "Good"
for i in 0..<3 {
  if( arr[i] == arr[i+1] ) {
    o = "Bad"
    break
  }
}

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

func main() {
    let s = Array(readLine()!)
    if s[0] == s[1] || s[1] == s[2] || s[2] == s[3] {
        print("Bad")
    } else {
        print("Good")
    }
}

main()
//  [typescript]
import { stringLiteral } from "@babel/types"

// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): { S: string } => {
  const S = lines[0]
  const obj = { S }
  debug(obj)
  return obj
}
// solver
export const solve = (lines: string[]): string => {
  const { S } = parseLines(lines)
  const str = S.split('')
  let current = str[0]
  for (let i = 1; i < S.length; i++) {
    if (current === str[i]) {
      return 'Bad'
    }
    current = str[i]
  }
  return 'Good'
}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [typescript]
import * as fs from "fs"
const process = (a: string[]): string => {
  for (let i = 0; i < a.length - 1; i++) {
    if (a[i] === a[i + 1]) {
      return "Bad"
    }
  }
  return "Good"
}

const Main = (input: string): string => {
  const a: string[] = input.split("")
  const res = process(a) + ""
  console.log(res)
  return res
}
Main(fs.readFileSync("/dev/stdin", "utf8"))
//  [typescript]
import { readFileSync } from 'fs'

function main(input: string) {
  const S = input.trim()

  console.log(/(.)\1+/.test(S) ? 'Bad' : 'Good')
}

main(readFileSync('/dev/stdin', 'utf8').trim())
//  [python]
n = int(input())
c = list(input())

r = []
for i in range(n):
    if c[i] == 'R':
        r.append(i)

count = 0
for i in range(len(r)):
    if r[i] != i:
        r.insert(i, i)
        r.pop()
        count += 1

print(count)
//  [python]
n = int(input())
s = input()
ans = 0

while True:
    if not ('R' in s and 'W' in s): break
    r = s.rindex('R')
    w = s.index('W')
    if r < w:
        break
    s = s[:w] + 'R' + s[w+1:r] + 'W' + s[r+1:]
    ans += 1
print(ans)
//  [python]
input()
c=input()
a=0
while 1:
	w=c.find('W')
	r=c.rfind('R')
	if w<0 or r<0 or r<w:break
	c=c[:w]+'R'+c[w+1:r]+'W'+c[r+1:]
	a+=1
print(a)
//  [java]
import java.util.*;

class Main{
    void solve(){
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        String s = scan.next();
        char[] c = new char[n];
        for(int i = 0; i < n; i++) c[i] = s.charAt(i);
        int out1 = 0;
        int cw = 0;
        for(int i = 0; i < n; i++) if(c[i] == 'W') cw++;
        out1 = Math.min(cw, n - cw);
        int out2 = 0;
        int w = 1;
        for(int i = 1; i < n; i++){
            if(c[i - 1] == 'W' && c[i] == 'W') w++;
            else{
                if(c[i - 1] != 'W') continue;
                int r = 0;
                for(int j = n - 1; j >= i; j--){
                    if(c[j] == 'R'){
                        r++;
                        c[j] ='W';
                        c[i - 1] = 'R';
                        if(r >= w) break;
                    }
                }
                out2 += r;
                w = 1;
            }
        }
        System.out.println(Math.min(out1, out2));
        scan.close();
    }
    public static void main(String[] args){
        new Main().solve();
    }
}
//  [java]
import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		// 整数の入力
		int N = Integer.parseInt(sc.next());
		//色の入力
		String c = sc.next();
		char[] C = new char[N];
		for (int i = 0; i < N; i++) {
			C[i] = c.charAt(i);
		}
		//赤だったら1、白だったら0で
		int[] nC = new int[N];
		for(int i=0;i<N;i++) {
		if(C[i]=='R') {
			nC[i]=1;
		}else {
			nC[i]=0;
		}
		}
		//左から白を探す→その白より右側に赤がある場合、一番右側にある赤とその白を入れ替える
		int check = 0;
		for (int j = 0; j < N/2; j++) {
			//白を検索
			int wn = N;//ホワイトナンバー
			for (int i = j; i < N; i++) {
				if (nC[i] == 0) {
					wn = i;
					break;
				}
			}
			//赤を探す
			int rn = N;//レッドナンバー
			for (int i = N - 1 - j; i >= 0; i--) {
				if (nC[i] == 1) {
					rn = i;
					break;
				}
			}
			//白と赤の場所比較して、場所入れ替え
			if (wn < rn && !(wn == 0 && rn == N)) {
				nC[wn] = 1;
				nC[rn] = 0;
				check++;
			}else {
				break;
			}
		}
		//

		System.out.println(check);
	}

}
//  [cpp]
#include <iostream>

int main() {
  int32_t n;
  std::cin >> n;

  std::string c;
  std::cin >> c;

  if (c.find('W') == std::string::npos) {
    std::cout << 0 << std::endl;
    return 0;
  }

  int32_t count = 0;
  for (;;) {
    auto r = c.find_last_of('R');
    auto w = c.find('W');
    if (r + 1 == w) {
      break;
    }
    auto tmp = c.at(w);
    c.at(w) = c.at(r);
    c.at(r) = tmp;
    ++count;
  }

  std::cout << count << std::endl;
  return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

#define gcd(a,b)		__gcd(a,b)
#define lcm(a,b)		(a*b)/gcd(a,b)
#define ff              first
#define ss              second
#define int             long long
#define pb              emplace_back
#define mp              make_pair
#define pii             pair<int,int>
#define vi              vector<int>
#define mii             map<int,int>
#define pqb             priority_queue<int>
#define pqs             priority_queue<int,vi,greater<int> >
#define setbits(x)      __builtin_popcountll(x)
#define zrobits(x)      __builtin_ctzll(x)
#define mod             1000000007
#define inf             INT_MAX
#define ps(x,y)         fixed<<setprecision(y)<<x
#define mk(arr,n,type)  type *arr=new type[n];
#define w(x)            int x; cin>>x; while(x--)
#define all(x)			x.begin(),x.end()
#define digits(x)		floor(log10(x))+1
#define FIO				ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0)

class dsu {
private:
	int *id;
	int* sz;

	int root(int i) {
		while (i != id[i]) {
			id[i] = id[id[i]];
			i = id[i];
		}
		return i;
	}
public:
	int n;
	dsu(int v) {
		n = v;
		id = new int[n];
		sz = new int[n];

		for (int i = 0; i < n; i++) {
			id[i] = i;
			sz[i] = 0;
		}
	}

	bool find(int p , int q) {
		return root(p) == root(q);
	}

	void join(int p , int q) {
		int i = root(p);
		int j = root(q);
		if (i == j) {
			return;
		}
		if (sz[i] < sz[j]) {
			id[i] = j ;
			sz[j] += sz[i];
		}
		else {
			id[j] = i;
			sz[i] += sz[j];
		}
	}
};

int nCr(int n , int r ) {
	int p = 1, k = 1;

	if (n - r < r ) {
		r = n - r;
	}
	if (r != 0) {
		while (r != 0) {
			p *= n ;
			k *= r ;
			int m = __gcd(p, k);
			p /= m;
			k /= m;
			n--;
			r--;
		}
	}
	else {
		p = 1;
	}
	return p ;
}

int modPower(int x, int y , int p) {
	//Used to calculate (x^y)%p
	int res = 1;
	if (y == 0) {
		return 1;
	}

	x = x % p;
	if (x == 0) {
		return 0  ;
	}

	while (y > 0) {
		if (y & 1) {
			res = (res * x) % p;
		}

		y >>= 1;
		x = (x * x) % p;
	}
	return res ;

}

bool allRed(string s) {
	bool ans = true;

	for (int i = 0 ; i  < s.length() ; i++) {
		if (s[i] != 'R') {
			ans = false;
			break;
		}
	}
	return ans;
}

bool allWhite(string s) {
	bool ans = true;

	for (int i = 0 ; i  < s.length() ; i++) {
		if (s[i] != 'W') {
			ans = false;
			break;
		}
	}
	return ans;
}


int bringRed(string s , int n) {

	int ans = 0 ;
	for (int i = 0 ; i < n ; i++) {
		if (s[i] == 'W') {
			int j = n - 1;
			while (s[j] != 'R' and j > i) {
				j--;
			}
			if (j == i) {
				break;
			}
			else {
				swap(s[i], s[j]);
				ans++;
			}
		}
	}
	return ans;

}


int32_t main() {
	FIO;


	int n ;
	cin >> n;

	string s ;
	cin >> s;


	int count = 0 ;
	// cout << count << "\n";
	if (allRed(s)) {
		count = 0;
	}
	if (allWhite(s)) {
		count = 0;
	}
	else {
		count = bringRed(s, n);
	}
	cout << count;








	return 0;
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
int main()
{
    ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
    int n,i;
    cin>>n;
    string s;
    cin>>s;
    int w=count(s.begin(),s.end(),'W'),r=n-w,wc=0;
    for(i=0;i<n;i++)
    {
        int c=0;
        if(s[i]=='W')
        {
            for(int j=n-1;j>=i;j--)
            {
                if(s[j]=='R')
                {
                    wc++;swap(s[i],s[j]);c=1;break;
                }

            }
            if(c==0)
                break;
        }
    }
    cout<<min(w,min(r,wc));

}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int	max(int a, int b)
{
  if (a > b)
    return (a);
  else
    return (b);
}

int	main(void)
{
  int	n;
  char	*s;
  int	i;
  int	nR;
  int	nW;
  char	*cR;
  char	*cW;
  char	*tmp;
  int	count;
  int	m;
  
  if (scanf("%d", &n) == EOF)
    return (-1);
  if (!(s = (char *)malloc((n + 1) * sizeof(char))))
    return (-1);
  s[n] = '\0';
  if (scanf("%s", s) == EOF)
  {
    free(s);
    return (-1);
  }
  i = 0;
  nR = 0;
  nW = 0;
  while (s[i])
  {
    if (s[i] == 'R')
      nR++;
    else if (s[i] == 'W')
      nW++;
    i++;
  }
  if (nR == 0 || nW == 0)
    printf("0\n");
  else
  {
    m = max(nR, nW);
    count = 0;
    while (count < m)
    {
	  	cW = strchr(s, 'W');
      	cR = strrchr(s, 'R');
      	if (cW > cR)
          break ;
      	else
        {
          *cW = 'R';
          *cR = 'W';
          count++;
        }
    }
    printf("%d\n", count);
  }
  free(s);
  return (0);
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <limits.h>
#include <time.h>
int main(){
    int n,i,r=0,ans=0;
    scanf("%d",&n);
    char c[n];
    for(i=0; i<n; i++){
        scanf("%s",&c);
    }
    for(i=0; i<n; i++){
        if(c[i]=='R')r++;
    }
    ans=r;
    for(i=0; i<r; i++){
        if(c[i]=='R')ans--;
    }
    printf("%d",ans);
    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <math.h>
 
int main(void) {
    int N;
    int numR = 0;
    int numW = 0;
    int numD = 0;
    char str[200000];
 
    scanf("%d\n", &N );
    
    for(int i = 0; i < N; i++) {
        scanf("%c", &str[i] );
        if( str[i] == 'R' ) {
            numR++;
        }
    }
 
    for(int i = 0; i < numR; i++) {
        if( str[i] == 'W' ) {
            numD++;
        }
    }
 
    printf("%d\n", numD);
 
    return 0;
}
//  [javascript]
process.stdin.resume();
process.stdin.setEncoding('utf-8');
 
let inputString = '';
let currentLine = 0;
 
process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});
 
process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    
    main();    
});
 
function readLine() {
    return inputString[currentLine++];
}

function main() {
  const n = Number(readLine())
  const cs = readLine()
  let s = 0, e = n - 1
  let result = 0
  const r = 'R', w = 'W'
  while (s <= e) {
    let wFound = false
    let rFound = false
    for (let i = s; i < e; i++) {
      if (cs[i] === r) {
        continue
      }
      wFound = true
      rFound = false
      for (let j = e; j > i; j--) {
        if (cs[j] === w) {
          continue
        }
        e = j - 1
        result += 1
        rFound = true
        break
      }
      if (!rFound) {
        break
      }
      s = i + 1
      break
    }
    if (!wFound || !rFound) {
      break
    }
  }
  console.log(result)
}
//  [javascript]
function main(input) {
    let lines = input.split("\n");
    let c = lines[1].split('');

    let cl = 0;
    let cr = c.length -1;
    let cnt = 0;
    while(true){
        cl = c.indexOf("W", cl);
        cr = c.lastIndexOf("R", cr);

        if(cl >= cr || cl === -1 || cr === -1){
            break;
        }

        let b = c[cl];
        c[cl] = c[cr];
        c[cr] = b;
        
        cnt++;
        cl++;
        cr--;
    }
    //console.log(c.join(""));

    return cnt;
}

//******************************
exports.main = main;

function Main(input) {
    console.log(main(input.trim()));
}

if (process.argv[2] !== "test") {
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [javascript]
function main(arg) {
    let n = Number(arg.split("\n")[0])
    let bit = arg.split("\n")[1].split("").map(x=>x=="W"?0:1)
    
    let w=0,r=0
    for(let i=0; i<n; i++) {
        if(bit[i]===0)w++
        else r++
    }
    w=0
    let min=n
    for(let i=0; i<=n; i++) {
        min = Math.min(min,Math.max(w,r))
//        console.log(`w=${w}, r=${r}, min=${min}`)
            if(bit[i]===0) {
                w++
            } else {
                r--
            }
    }
    console.log(min)
    
}


main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
package main

import (
	"fmt"
	"math"
	"strings"
)

func main() {
	var n int
	fmt.Scanf("%d", &n)
	var s string
	fmt.Scanf("%s", &s)

	list := strings.Split(s, "")
	fmt.Println(countPair(list))
}

func countPair(list []string) int {
	var rc, wc int
	for _, v := range list {
		if v == "W" {
			wc++
		}
		if v == "R" {
			rc++
		}
	}

	var ret int
	var l_rc, r_wc int
	r_wc = 0
	l_rc = rc
	ret = max(rc, wc)
	//fmt.Println(ret)
	for _, v := range list {
		tmp := max(r_wc, l_rc)
		if ret > tmp {
			ret = tmp
		}
		if v == "W" {
			r_wc++
		}
		if v == "R" {
			l_rc--
		}
	}
	tmp := max(r_wc, l_rc)
	if ret > tmp {
		ret = tmp
	}
	return ret
}

func max(a int, b int) int {
	return int(math.Max(float64(a), float64(b)))
}
//  [go]
package main

import (
  "fmt"
)

func main() {
  initialStones := readProblem()
  minOperationCount := getMinOperationCount(initialStones)
  fmt.Println(minOperationCount)
}

func getMinOperationCount(initialStones []Color) int {
  whiteOnLeft := 0
  redOnRight := 0
  for _, stone := range initialStones {
    if stone == RED {
      redOnRight++
    }
  }
  
  minOperationCount := len(initialStones) // effectivery infinity
  separator := 0
  for separator <= len(initialStones) {
    operationCount := max(whiteOnLeft, redOnRight)
    if minOperationCount > operationCount {
      minOperationCount = operationCount
    }

    if separator < len(initialStones) {
      if initialStones[separator] == RED {
        redOnRight--
      } else {
        whiteOnLeft++
      }
    } else {
      // we already have minimum value
      // so we don't have anything to do here.
    }
    separator++
  }
  return minOperationCount
}

func max(a, b int) int {
  if a <= b {
    return b
  }
  return a
}

func readProblem() []Color {
  var stoneCount int
  fmt.Scan(&stoneCount)
  var stoneMarks string
  fmt.Scan(&stoneMarks)
  stones := make([]Color, stoneCount)
  idx := 0
  for idx < stoneCount {
    stones[idx] = ReadColor(stoneMarks[idx])
    idx++
  }
  return stones
}

type Color int
const (
  RED Color = iota
  WHITE
)
func ReadColor(colorStr byte) Color {
  if colorStr == 'R' {
    return RED
  }
  return WHITE
}
//  [ruby]
n = gets.to_i
c = gets.chomp
r = c.scan('R').length
d = "R" * r + "W" * (n - r)

res = 0
r.times do |i|
  if c[i] != d[i]
    res += 1
  end
end

puts res
//  [ruby]
n = gets.chomp.to_i
values = gets.chomp

count = 0
loop do
  w_pos = values.index('W')
  r_pos = values.rindex('R')
  
  if w_pos == nil || r_pos == nil
    break
  end

  if w_pos > r_pos
    break
  end

  values[w_pos] = 'R'
  values[r_pos] = 'W'
  count += 1
end

puts count
//  [ruby]
N = gets.chomp.to_i
C = gets.chomp.split("")

$WI = 0
$RI = C.size - 1

def wi()
  for i in $WI...C.size do
    return i if C[i] == "W"
  end
  nil
end

def ri()
  $RI.downto(0) do |i|
    return i if C[i] == "R"
  end
  nil
end

cnt = 0
while true do
  wi = wi()
  ri = ri()

  break if wi == nil || ri == nil
  break if wi >= ri
  C[wi] = "R"
  C[ri] = "W"
  $WI = wi
  $RI = ri
  cnt += 1
end
puts cnt
//  [rust]
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::{Bytes, Chars};
#[allow(unused_imports)]
use std::cmp::{min, max};

fn main() {
	input! {
		_n: usize,
		mut cs: Chars,
	}

	let mut ans = 0;
	loop {
		// 先頭から続く赤を右方向に消していく
		loop {
			if 0 < cs.len() && cs[0] == 'R' {
				cs.remove(0);
			}
			else {
				break;
			}
		}
		if cs.len() == 0 {
			println!("{}", ans);
			return;
		}
		// 末尾から続く白を左方向に消していく
		loop {
			if 0 < cs.len() && cs[cs.len()-1] == 'W' {
				cs.remove(cs.len()-1);
			}
			else {
				break;
			}
		}
		if cs.len() == 0 {
			println!("{}", ans);
			return;
		}
		loop {
			// 先頭が白で末尾が赤ならそれぞれ削除して答えを＋＋
			if cs[0] == 'W' && cs[cs.len()-1] == 'R' {
				cs.remove(0);
				cs.remove(cs.len()-1);
				ans += 1;
				if cs.len() == 0 {
					println!("{}", ans);
					return;
				}
			}
			else {
				break;
			}
		}
	}
}
//  [rust]
use proconio::input;
use proconio::marker::{Chars};

// x ** n % mods を求める
pub fn mod_pow(x: i64, n: i64, mods: i64) -> i64 {
    if n == 0 {
        return 1;
    }
    let mut res = mod_pow(x * x % mods, n / 2, mods);
    if n % 2 == 1 {
        res = res * x % mods;
    }
    return res;
}

// (1/n) % mods を求める
pub fn mod_inv(n: i64, mods: i64) -> i64 {
    return mod_pow(n, mods-2, mods);
}

// nCk % mods を求める
pub fn mod_comb(n: i64, k: i64, mods: i64) -> i64 {
    let sum1 = (n-k+1..n+1).fold(1, |ac, x| ac * x % mods);
    let sum2 = (1..k+1).fold(1, |ac, x| ac * x % mods);
    return sum1 * mod_inv(sum2, mods) % mods;
}

// nCk の組み合わせを列挙する
pub fn combination(n: usize, k: usize) -> Vec<Vec<usize>> {
    let mut ans = Vec::new();
    if k == 1 {
        for i in 1..n+1 {
            let mut tmp = Vec::new();
            tmp.push(i);
            ans.push(tmp);
        }
    }
    else {
        for iter in combination(n-1, k-1) {
            let max = iter.iter().max().unwrap();
            for j in *max+1..n+1 {
                let mut tmp = iter.clone();
                tmp.push(j);
                ans.push(tmp);
            }
        }
    }
    ans
}

use std::collections::VecDeque;

fn main() {
    input!{
        n: usize,
        mut c: Chars,
    }
    let mut ans = 0;
    let mut bufr = VecDeque::new();
    let mut bufw = VecDeque::new();
    for i in (0..n).rev() {
        if c[i] == 'R' {
            bufr.push_back(i);
        }
    }
    for i in 0..n {
        if c[i] == 'W' {
            bufw.push_back(i);
        }
    }
    loop {
        let mut flag = 0;
        for i in bufw.iter().rev() {
            if *i < n-1 {
                if c[*i+1] == 'R' {
                    c.swap(bufw.pop_front().unwrap(), bufr.pop_front().unwrap());
                    flag = 1;
                    ans += 1;
                    break;
                }
            }
        }
        if flag == 0 {
            println!("{}", ans);
            return;
        }
    }
}
//  [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 arr: String = read();
    let arr: Vec<char> = arr.chars().collect();
    let mut r = Vec::new();
    let mut w = Vec::new();
    for i in 0..n {
        if arr[i] == 'R' {
            r.push(i);
        } else {
            w.push(i);
        }
    }
    if w.is_empty() || r.is_empty() {
        println!("0");
    } else {
        let mut ans = 0;
        while r.last().unwrap() > w.first().unwrap() {
            r.pop();
            w.remove(0);
            ans += 1;
            if r.is_empty() || w.is_empty() {
                break;
            }
        }
        println!("{}", ans);
    }
}
//  [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 gcd(_ m:Int, _ n:Int) -> Int {
    if n == 0 {return m}
    return gcd(n, m % n)
}
///最小公倍数を返す
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://melheaven.hatenadiary.jp/entry/atcoder144
///約数の配列を返す
func makeDivisors(_ n:Int) -> [Int] {
    var divisors = [Int]()
    for i in 1..<Int(pow(Double(n), 0.5)) + 1 {
        if n % i == 0{
            divisors.append(i + n / i)
        }
    }
    
    return divisors
}

//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
}

func main() {
    let n = readInt()
    let aryC = readLine()!.map { String($0) }
    //＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿＿ここまで入力
    let rStones = aryC.filter { $0 == "R"}.count
    let ans = aryC[..<rStones].filter { $0 == "W"}.count
    
    print(ans)
}
main()
//  [swift]
import Foundation

class Scanner {
    static func readInt() -> Int {
        return Int(readLine()!)!
    }
    
    static func readIntArr() -> [Int] {
        return readLine()!.split(separator: " ").map { Int($0)! }
    }
    
    static func readM(_ n: Int) -> [[Int]] {
        var res = [[Int]]()
        for _ in 0..<n {
            res.append(readIntArr())
        }
        return res
    }
    
    static func readUknownIntMat() -> [[Int]] {
        var res = [[Int]]()
        while let line = readLine() {
            res.append(line.split(separator: " ").map { Int($0)! })
        }
        return res
    }
    
    static func readString() -> String {
        return readLine()!
    }
}

class Printer {
    static func printIntArray(_ arr: [Int]) {
        print(arr.map { String($0) }.joined(separator: " "))
    }
}

class Solution {
    func minSwaps(_ str: String) -> Int {
        var res = 0, left = 0, right = str.count-1
        let str = Array(str)
        
        //WRWWRWRR
        while left<right {
            while left < right && str[left] != "W"  {
                left += 1
            }
            while right > left && str[right] != "R" {
                right -= 1
            }
            if str[left] == "W" && str[right] == "R" {
                res += 1
            }
            left += 1
            right -= 1
        }
        return res
    }
}


let n = Scanner.readInt()
let str = Scanner.readString()
print(Solution().minSwaps(str))
//  [typescript]
{
  const run = (input: string) => {
    let split = input.trim().split("\n")
    const n: number = parseInt(split[0])
    const stones: string[] = split[1].split("")

    const whites = []
    stones.forEach((v: string, i: number) => {
      if (v === 'W') whites.push(i)
    })

    let count = 0
    for (let i = 1; i <= n; i++) {
      if (stones[n - i] === 'R') {
        const v = whites.shift()
        if (v != null && v < n - i) {
          stones[v] = 'R'
          count++
        }
      }
    }

    return count
  }

  const Main = (input: string) => {
    console.log(run(input))
  };

  Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}
//  [typescript]
import { readFileSync } from "fs";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const range = (n: number | bigint) => [...Array(Number(n))].map((_, i) => i);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const tuple = <T extends unknown[]>(...ts: T) => ts;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [cin, nCin, biCin] = (() => {
  const inputs = readFileSync("/dev/stdin", "utf-8").split(/[\n|\s]+/);
  let count = 0;
  const cin = () => inputs[count++];
  return tuple(
    cin,
    () => Number(cin()),
    () => BigInt(cin())
  );
})();

type Color = "R" | "W";

// 1. R...R
// 2. W...W
// 3. R...RW...W
const getAnswer = (N: number, cs: Color[]): number => {
  const rNum = cs.filter((c) => c === "R").length;

  return [
    rNum,
    N - rNum,
    cs.slice(0, rNum).filter((c) => c === "W").length,
  ].reduce((acc, n) => Math.min(acc, n));
};

{
  const N = nCin();
  const cs = cin()
    .split("")
    .map((c) => c as Color);
  const ans = getAnswer(N, cs);
  console.log(ans);
}
//  [typescript]
import { readFileSync } from "fs";

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const range = (n: number | bigint) => [...Array(Number(n))].map((_, i) => i);
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const tuple = <T extends unknown[]>(...ts: T) => ts;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const [cin, nCin, biCin] = (() => {
  const inputs = readFileSync("/dev/stdin", "utf-8").split(/[\n|\s]+/);
  let count = 0;
  const cin = () => inputs[count++];
  return tuple(
    cin,
    () => Number(cin()),
    () => BigInt(cin())
  );
})();
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isNumber = (x: unknown): x is number => typeof x === "number";
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const isBigint = (x: unknown): x is bigint => typeof x === "bigint";
type NumberOrBigintOrElse<T> = number | bigint extends T
  ? undefined
  : T extends number
  ? number
  : T extends bigint
  ? bigint
  : undefined;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const max = <T extends number | bigint>(...ts: T[]): NumberOrBigintOrElse<T> =>
  (ts.length === 0
    ? undefined
    : isNumber(ts[0])
    ? Math.max(...(ts as number[]))
    : (ts as bigint[]).reduce((acc, t) =>
        acc >= t ? acc : t
      )) as NumberOrBigintOrElse<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const min = <T extends number | bigint>(...ts: T[]): NumberOrBigintOrElse<T> =>
  (ts.length === 0
    ? undefined
    : isNumber(ts[0])
    ? Math.min(...(ts as number[]))
    : (ts as bigint[]).reduce((acc, t) =>
        acc <= t ? acc : t
      )) as NumberOrBigintOrElse<T>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const abs = <T extends number | bigint>(t: T): NumberOrBigintOrElse<T> =>
  (isNumber(t)
    ? Math.abs(t)
    : isBigint(t)
    ? t >= 0n
      ? t
      : -t
    : undefined) as NumberOrBigintOrElse<T>;

/**
 * Program
 */
type Color = "R" | "W";

const getAns = (N: number, cs: Color[]): number => {
  const rNum = cs.filter((c) => c === "R").length;
  return min(rNum, N - rNum, cs.slice(0, rNum).filter((c) => c === "W").length);
};

{
  const N = nCin();
  const cs = cin()
    .split("")
    .map((c) => c as Color);
  const ans = getAns(N, cs);
  console.log(ans);
}
//  [python]
N, K = map(int, input().split())
A = list(map(lambda a: int(a) - 1, input().split()))

T = [A]
for _ in range(64):
    prev = T[-1]
    T.append([prev[a] for a in prev])

now = 0
for d, P in enumerate(T):
    if ((1 << d) & K) > 0:
        now = P[now]
print(now + 1)
//  [python]
import sys

int1 = lambda x: int(x) - 1
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int1, readline().split()))
prn = lambda x: print(*x, sep='\n')

n, k = nm()
m = 64
a = nl()
table = list()
table.append(a)
for _ in range(m-1):
    f = table[-1]
    g = [f[f[i]] for i in range(n)]
    table.append(g)
crt = 0
for i in range(m):
    if k & 1:
        crt = table[i][crt]
    k >>= 1
print(crt + 1)
//  [python]
n, k = map(int, input().split())
a = [int(i) - 1 for i in input().split()]
ans = 0
while k:
    if k & 1:
        ans = a[ans]
    c = [a[a[i]] for i in range(n)]
    a = c[:]
    k >>= 1
print(ans + 1)
//  [java]
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {
	//java11

	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);

		int N = sc.nextInt();
		long K =sc.nextLong();

		//テレポート先
		int[] A = new int[N+1];

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

		int ans = 1;
		long index = 1;

		//loop考慮なし
		if(K <=N) {

			while(index <= K) {
				ans = A[ans];
				index++;
			}

		}
		else {
			//loopを検出
			boolean[] checked = new boolean[N+1];
			Arrays.fill(checked, false);
			List<Integer> loop = new ArrayList<>();
			int before_loop_n = 0;

			while(index <= K) {
				loop.add(ans);
				checked[ans] = true;

				//loopの終わり
				if(checked[A[ans]]) {
					//先頭からA[ans]の前までを削除
					int a = 1;
					while(a != A[ans]) {
						loop.remove(0);
						before_loop_n++;
						a = A[a];
					}
					break;
				}

				ans = A[ans];
				index++;
			}

			ans = 1;
			index = 1;
			if(K <= before_loop_n-1) {
				while(index <= K) {
					ans = A[ans];
					index++;
				}
			}
			else {
				int loop_index = (int)((K - before_loop_n) % loop.size());
				ans = loop.get(loop_index);
			}
		}

		System.out.println(ans);
	}

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

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        final int N = sc.nextInt();
        final long K = sc.nextLong();
        int[] teleport = new int[N];
        for(int i=0; i<N; i++) {
            teleport[i]=sc.nextInt()-1;
        }

        boolean[] clear = new boolean[N];
        clear[0] = true;

        List<Integer> list = new ArrayList<>();     //<>の中のIntegerは冗長なのでいらないって言われます。実際めんどくさいので消してOK
        list.add(0);

        int twice = -1;     //初めて2回目に踏む町の番号(0<=twice<=N-1)

        for(int i=0; i<K; i++) {
            int x= teleport[list.get(i)];
            if(clear[x]) {      //既に踏んでいる町なら
                twice = x;      //twiceにxを代入しbreak
                break;
            }else {             //まだ踏んでない町なら
                list.add(x);    //行程をlistに記録して
                clear[x] = true;    //踏んだという印をつける
            }
        }

        /*
        ここまでで、もしループを踏む前に走査が終わった場合
        listの中身は{0, (0からテレポした先), (さらにテレポした先), ...}という風になって、
        そのsize()はK+1です。
        ただし、K回目にclear[x]==trueであった時、twiceを記録してbreakしてしまうので、
        twice==-1とは限りません。
         */

        if(twice==-1) {
            System.out.println(list.get((int)K)+1);     //ここが変更点。ループ到達前に走査が終わった場合は、「リストの最後の町」がそのまま答えになるはず。なおこの場合Kの大きさはたかだか2×10^5なのでテキトーにintにキャストしてよい。
        }else {
            int num =0;
            while(!list.isEmpty()) {      //小変更。好みの問題。
                if(list.get(0)==twice) {    //ループ開始点まで来たらそこで止める
                    break;
                }else {
                    list.remove(0);     //ループ開始点に到達するまで先頭の要素を消し続ける。最終的にループ構造だけが残る
                    num++;      //numでループの先頭までのステップ数を記録する
                }
            }

            /*
            K-num = ループの先頭に到達したあとさらに動かなければいけないステップ数
            list.size = ループ長
            なので、
             */

            System.out.println(list.get((int)((K-num)%list.size()))+1);     //これでOK。
        }
    }
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
int main()
{
    ios::sync_with_stdio(0), cin.tie(0);
    int n;
    long long k;
    cin >> n >> k;
    vector<int> town(n + 1);
    vector<bool> visit(n + 1, false);
    for (int i = 1; i <= n; i++)
    {
        int to;
        cin >> to;
        town[i] = to;
    }
    int now = town[1];
    visit[now] = true;
    vector<int> loop;
    visit[1] = true;
    k--;
    while (k != 0)
    {
        now = town[now];

        if (!visit[now])
        {
            visit[now] = true;
        }
        else
        {
            if (find(loop.begin(), loop.end(), now) != loop.end())
            {
                k--;
                break;
            }
            loop.push_back(now);
        }
        k--;
    }
    if (k > 0)
    {
        long long pos = k % loop.size();
        // cout << "pos = " << k << " % " << loop.size() << "= " << pos << endl;
        // cout << loop[pos] << endl;
        // for (auto &i : loop)
        // {
        //     cout << i << " ";
        // }
        cout << loop[pos];
    }
    else
        cout << now;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
int main()
{
    ios::sync_with_stdio(0), cin.tie(0);
    int n;
    long long k;
    cin >> n >> k;
    vector<int> town(n + 1);
    vector<bool> visit(n + 1, false);
    for (int i = 1; i <= n; i++)
    {
        int to;
        cin >> to;
        town[i] = to;
    }
    int now = town[1];
    visit[now] = true;
    vector<int> loop;
    visit[1] = true;
    k--;
    while (k != 0)
    {
        now = town[now];

        if (!visit[now])
        {
            visit[now] = true;
        }
        else
        {
            if (find(loop.begin(), loop.end(), now) != loop.end())
            {
                k--;
                break;
            }
            loop.push_back(now);
        }
        k--;
    }
    if (k > 0)
    {
        long long pos = k % loop.size();
        cout << loop[pos];
    }
    else
        cout << now;
}
//  [cpp]
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false); cin.tie(NULL);
#define ll long long
#define ull unsigned long long
#define FI(i,a,n) for(int i=a; i<=n; i++)
#define RFI(i,n,a) for(int i=n; i>=a; i--)
#define FLL(i,a,n) for(ll i=a; i<=n; i++)
#define RFLL(i,n,a) for(ll i=n; i>=a; i--)
#define vi vector<int>
#define vll vector<ll>
#define all(v) v.begin(),v.end()
#define pll pair<ll,ll>
#define pi pair<int, int>
#define GCD(a,b) __gcd(a,b)
#define MP make_pair
#define PB push_back
#define PF push_front
#define LB lower_bound
#define UB upper_bound
#define debug(x) cout << x << endl
#define MOD 1000000007
#define INF LLONG_MAX
#define PI 3.14159265359
using namespace std;


int main()
{
  fastio
  int n;
  ll k;
  cin >> n >> k;
  int a[n+1];
  for(int i=1; i<=n; i++) cin >> a[i];
  vi cycle;
  /* cycle.PB(1); */
  int i=a[1];
  map<int, int> m;
  /* m[1]=1; */
  /* while(i!=1) cycle.PB(i), i=a[i], cout << i; */
  while(!m.count(i)) cycle.PB(i), m[i]=1, i=a[i] ;
  int start = a[cycle.back()];
  vi edge;
  while(cycle[0]!=start)
  {
    edge.PB(cycle[0]);
    cycle.erase(cycle.begin());
  }
  if(k<=edge.size())
  {
    cout << edge[k-1] ;
    return 0;
  }
  k -= edge.size();
  int len = cycle.size();
  k--;
  k%=len;
  

  /* for(auto &j:cycle) cout << j << " "; */
  cout << cycle[k];

  return 0;
}
//  [c]
#include<stdio.h>
#include<string.h>
int main() {
    int n;
    long long k;scanf("%d %llu",&n,&k);
    int a[n];for(int i=0;i<n;i++)scanf("%d",&a[i]);
    
    int next=0;
    int cnt=0;
    int table[600000]={};
    static int proc[600000]={};
    proc[0]=1;
    table[0]++;
    int flg;
    for(int i=0;i<2*n;i++){
        int next = a[next] - 1;
        proc[i+1]=next+1;
        if(table[next]>=1){flg=next+1;break;}
        
        table[next]++;
    }
    fprintf(stderr,"flg:%d\n", flg);
    int start=-1,end=-1;
    for(int i=0;i<2*n;i++){
        fprintf(stderr,"%d ",proc[i]);
        if(proc[i]==flg){
            if(start==-1)start=i;
            else if(end==-1)end=i;
        }
        if(end!=-1)break;
    }
    fprintf(stderr,"\n");
    int range = end-start;
    fprintf(stderr, "%d %d %d\n",start,end,range);

    int c=0;
    if(flg==1){
        c=0;
    }else{
        for(int i=1;i<n;i++){
            if(proc[i]==flg){
                c=i;
                break;
            }
        }
    }
    fprintf(stderr,":%d\n",c);
    fprintf(stderr,"::%lld\n",(k-c));
    if(k-c<0)printf("%d\n",proc[k]);
    else printf("%d\n",proc[c+(k-c)%range]);
}
//  [c]
#include <stdio.h>
#include <inttypes.h>

int N;
int A[271828];
uint64_t K;

int dest[281828][70];

int main(void) {
	int i, j;
	int mofu = 1;
	if (scanf("%d%" SCNu64, &N, &K) != 2) return 1;
	for (i = 1; i <= N; i++) {
		if (scanf("%d", &A[i]) != 1) return 1;
	}
	for (i = 1; i <= N; i++) {
		dest[i][0] = A[i];
	}
	for (j = 1; j < 70; j++) {
		for (i = 1; i <= N; i++) {
			dest[i][j] = dest[dest[i][j - 1]][j - 1];
		}
	}
	for (i = 0; i < 64; i++) {
		if ((K >> i) & 1) mofu = dest[mofu][i];
	}
	printf("%d\n", mofu);
	return 0;
}
//  [c]
#include<stdio.h>
long long n,m,d[100][200010],p=1,i,j;
int main(){
  scanf("%lld %lld",&n,&m);
  for(i=0;i<n;i++)scanf("%lld",&d[0][i+1]);
  for(i=0;i<70;i++){
    for(j=1;j<=n;j++)d[i+1][j]=d[i][d[i][j]];
  }
  for(i=0;i<64;i++){
    if(((1LL<<i)&m))p=d[i][p];//printf("%lld %lld\n",(1LL<<i),p);
  }
  printf("%lld\n",p);
  return 0;
}
//  [javascript]
/* 別解のダブリングというテクニックを使って解いてみる */
function main(input) {
  let [n, k] = input[0].trim().split(" ").map(i => BigInt(i));
  const a = input[1].trim().split(" ").map(i => parseInt(i-1));

  //2**?の深さを確かめる
  let max_depth = 0n;
  while(true){
    max_depth++;
    if(2n**max_depth>k){
      max_depth--;
      break;
    }
  }

  /* ダブリングによるマップを作る */
  let map = [];
  map[0] = a;
  for(let i=1;i<=max_depth;i++){
    map[i] = [];
    for(let j=0;j<n;j++){
      map[i][j]= map[i-1][map[i-1][j]];
    }
  }

  //k番目の要素までの経路を作成する
  let map_load = [];
  for(let i=max_depth;i>=0n;i--){
    let pow2 = 2n**i;
    if(k>=pow2){
      for(let j=0n;j<(k/pow2);j++){
        k-=pow2;
        map_load.push(i);
      }
    }
    if(k===0n){
      break;
    }
  }
  //経路通りに辿って答えを見つける
  let now = 0;
  for(let i of map_load){
    now=map[i][now];
  }

  console.log((now+1)+"");
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));
//  [javascript]
const processData = (lines) => {
  let [n, k] = lines[0].split(' ').map(x => BigInt(x))
  const towns = lines[1].split(' ').map(x => +x)

  const map = {}
  const cycle = []
  let startSlice = 0
  let pos = 0
  while(map[pos]!== 2) {
    map[pos] = map[pos] ? map[pos] + 1 : 1
    cycle.push(pos)
    pos = towns[pos] - 1
  }

  const double = Object.entries(map).find(([key, value]) => value === 2)

  const startPoint = cycle.findIndex(x => x == double[0])

  const cycleLen = cycle.slice(startPoint+1).findIndex(x => x == double[0])+1

  const refCycle = cycle.slice(startPoint, startPoint+cycleLen)

  // console.log(refCycle, startPoint)

  // console.log(k)

  if (k <= BigInt(startPoint)) {
    console.log(cycle[k]+1)
  } else {
    const inCycle = k - BigInt(startPoint)
    // console.log(inCycle)
    console.log(refCycle[inCycle % BigInt(refCycle.length)]+1)
  }

  // const t = k % BigInt(refCycle.length)

  // console.log(cycle[t])

  // while (k) {
  //   pos = towns[pos] - 1
  //   k = k - BigInt(1)
  // }
  // console.log(pos)
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
  const {EOL} = require('os')
  const lines = i.split(EOL) /*your input text, split by lines*/
  processData(lines)
})
//  [go]
package main

import (
	"fmt"
)

func main() {
	var N, K int
	fmt.Scanf("%d %d", &N, &K)

	as := make([]int, N)
	for i := range as {
		fmt.Scan(&as[i])
		as[i]--
	}

	var count int
	m := make(map[int]int)
	m[0] = 0
	ts := make([]int, 0)
	ts = append(ts, 0)

	for count < K {
		last := ts[len(ts)-1]
		next := as[last]
		if p, ok := m[next]; ok {
			cycle := count - p + 1
			offset := (K - p) % cycle
			fmt.Println(ts[p+offset] + 1)
			return
		}
		count++
		m[next] = count
		ts = append(ts, next)
	}
	fmt.Println(ts[len(ts)-1] + 1)
}
//  [go]
package main

import "fmt"

func main() {
	var N, K int
	fmt.Scanf("%d %d", &N, &K)

	A := make([]int, N)
	for i := range A {
		fmt.Scanf("%d", &A[i])
		A[i]--
	}

	last := 0
	count := 0
	m := make(map[int]int) // m[city] = count
	history := make([]int, 0)
	m[0] = 0
	history = append(history, 0)

	for count < K {
		next := A[last]
		if past, ok := m[next]; ok {
			cycle := count - past + 1
			offset := (K - past) % cycle
			fmt.Println(history[past+offset] + 1)
			return
		}

		// update
		count++
		m[next] = count
		history = append(history, next)
		last = next
	}

	fmt.Println(last + 1)
}
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n, k int
	fmt.Scan(&n, &k)
	var a = make([]int, n+1)
	var time = make([]int, n+1)
	visited := []int{1}
	for i := 1; i <= n; i++ {
		fmt.Scan(&a[i])
	}
	tmp := 1
	for i := 1; i <= k; i++ {
		next := a[tmp]
		if time[next] != 0 {
			cycle := i - time[next]
			dest := (k-time[next])%cycle + time[next]
			tmp = visited[dest]
			break
		}
		time[next] = i
		visited = append(visited, next)
		tmp = next
	}
	fmt.Print(tmp)
}
//  [ruby]
#ダブリングを使う、２進数
N,K = gets.strip.split.map(&:to_i)
num = gets.strip.split.map(&:to_i)
t = Math.log2(K).ceil

#数表を作っていく、そしてそこに記録して後々使う
db = Array.new(t+1){Array.new(N+1,0)} #二次元配列の初期化に注意
for i in 1..N #初期条件
  db[0][i] = num[i-1]
end
for k in 1..t
  for i in 1..N
    db[k][i] = db[k-1][db[k-1][i]]
  end
end

m = K.to_s(2) #２進数に直した,ただしmの各数字は文字メソッド（.to_s)だよ
now = 1
for j in 0..m.size-1
  if m[j] == "1"
    now = db[m.size-1-j][now]
  end
end
puts now
//  [ruby]
eval"N,K,*A="+`dd`.split*?,
E=*1..N
60.times{|i|K[i]>0&&E.map!{A[_1-1]}
A=A.map{A[_1-1]}}
p E[0]
//  [ruby]
eval"N,K,*A="+`dd`.split*?,
E=*1..N
p E[0.upto(60){K%2>0&&E.map!{A[_1-1]}
A=A.map{A[_1-1]}
K/=2}]