akhauriyash/Code-Regression huggingface dataset:
#include <iostream>
#include <sstream>
#include <stack>
#include <iomanip>
#include <string>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <queue>
#include <cmath>

#define BEGIN(x) x.begin()
#define END(x) x.end()
#define ALL(x) BEGIN(x), END(x)
#define PAIR make_pair
#define VEC(type) vector<type >

#define FOR(i, A, B) for(auto i = (A);i != (B); i++)
#define FORD(i, A, B) for(auto i = (A);i != (B); i--)

#define READRANGE(begin, end) FOR(it, begin, end) cin >> *it
#define READVEC(V) READRANGE(BEGIN(V), END(V))

using namespace std;

typedef long long lint;
typedef pair<int, int> Pii;
typedef pair<int, lint> Pil;
typedef pair<lint, lint> Pll;
typedef pair<lint, int> Pli;

// ---- BEGIN LIBRARY CODE ----
// ---- END LIBRARY CODE ----
void io_init()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
};

int main(int argc, char **argv)
{
    io_init();

    // Actual program code starts here.
    int N, M;
    cin >> N >> M;
    VEC(int) X(M);
    READVEC(X);
    sort(ALL(X));
    VEC(int) diffs(M - 1);
    FOR(i, 0, M - 1)
        diffs[i] = X[i + 1] - X[i];
    sort(ALL(diffs));
    reverse(ALL(diffs));
    N = min(N, M) - 1;
    int ret = 0;
    FOR(i, N, diffs.size())
        ret += diffs[i];
    cout << ret << endl;
    return 0;
};


Measured memory_bytes: 1024
# 羊、狼をそれぞれ1,0と表記する
# 回答o,xをそれぞれ1,0と表記する

N = int(input())
s = list(input().replace("o", "1").replace("x", "0"))
s = list(map(int, s))

# 隣接する2匹の動物と右側の動物の回答を受けて、次の動物を返す
def next_animal(animal1, animal2, answer2):
    if (animal2 == 1 and answer2 == 1) or (animal2==0 and answer2==0):
        return animal1
    else:
        return 1^animal1

# 隣接する2匹の動物のパターン4通り×円順列に対するパターンN通りを試す
for first_two_animals in [[1,1],[1,0],[0,1],[0,0]]:
    animal_list = []
    animal_list.append(first_two_animals[0])
    animal_list.append(first_two_animals[1])

    for idx in range(2,N):
        animal_list.append(next_animal(animal_list[idx-2], animal_list[idx-1], s[idx-1]))

    # N番目の動物と回答が、状況と矛盾していないか確かめる
    if (s[0]==1 and animal_list[0]==1) or (s[0]==0 and animal_list[0]==0):
        last_animal = animal_list[1]
    else:
        last_animal = 1^animal_list[1]

    if (last_animal==1 and (animal_list[-2] == animal_list[0])) or (last_animal==0 and (animal_list[-2] != animal_list[0])):
        last_answer = 1
    else:
        last_answer = 0

    if last_animal == animal_list[-1] and last_answer == s[-1]:
        animal_list = list(map(str, animal_list))
        animal_list = [x.replace("1", "S").replace("0", "W") for x in animal_list]
        print("".join(animal_list))
        exit()

print(-1)

Measured memory_bytes: 16408
#include <bits/stdc++.h>

using namespace std;

#define pb push_back
#define mp make_pair
#define forn(i, n) for (int i = 0; i < (int)(n); ++i)
typedef long long LL;
typedef pair<int, int> PII;

LL n;

int main() {
    ios_base::sync_with_stdio(false);
    cin >> n;
    --n;
    LL cnt = 26;
    int len = 1;
    while (cnt <= n) {
        n -= cnt;
        cnt *= 26;
        ++len;
    }
    string ans(len, 'a');
    forn(i, len) {
        ans[len - 1 - i] = 'a' + (n % 26);
        n /= 26;
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 3588
package main

import (
	"fmt"
	"sort"
)

func scanNums(len int) []int {
	var num int
	var nums []int
	for i := 0; i < len; i++ {
		fmt.Scan(&num)
		nums = append(nums, num)
	}
	return nums
}

func main() {
	var N int
	var result int
	fmt.Scan(&N)
	arr := scanNums(N)
	sort.Sort(sort.Reverse(sort.IntSlice(arr)))

	for i, v := range arr {
		if i%2 == 0 {
			result += v
		} else {
			result -= v
		}
	}

	fmt.Println(result)
}


Measured memory_bytes: 512
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int n;
    cin >> n;
    vector<long long> a(n), cnt(n, 0);
    for (int i=0; i<n; i++) {
        cin >> a[i];
        a[i]--;
        cnt[a[i]]++;
    }

    long long ans = 0;
    for (auto ci : cnt) {
        if (ci < 2) continue;
        ans += ci * (ci-1) / 2;
    }

    for (auto ai : a)
        cout << ans - (cnt[ai]-1) << endl;
}


Measured memory_bytes: 5760
#include <stdio.h>
int main(){
  int N,K,X,Y,ans1,ans2;
  scanf("%d",&N);
   scanf("%d",&K);
   scanf("%d",&X);
   scanf("%d",&Y);
  if(N>K){
  ans1=K*X;
  ans2=(N-K)*Y;
  printf("%d\n",ans1+ans2);
  }
  else printf("%d\n",N*X);
  return 0;
}


Measured memory_bytes: 128
use std::io;
use std::str::FromStr;

fn input<T:FromStr>() -> T {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    line.trim().parse().ok().unwrap()
}

fn input_vec() -> Vec<String> {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    line.split_whitespace().map(|s| s.to_string()).collect()
}

fn binary_search<F>(mut ok: i32, mut ng: i32, is_ok: F) -> i32
    where
        F: Fn(usize) -> bool
    {
        while (ok - ng).abs() > 1 {
            let mid = (ok + ng) / 2;
            if is_ok(mid as usize) {
                ok = mid;
            } else {
                ng = mid;
            }
        }
        ok
}

fn main() {
    let n: u64 = input();
    let s: String = input();
    let mut s: Vec<char> = s.chars().collect();
    let q: u64 = input();
    let mut char_indices: Vec<Vec<usize>> = vec![Vec::new(); 26];
    for i in 0..s.len() {
        // println!("{}", s[i] as usize - 49);
        char_indices[s[i] as usize - 97].push(i);
    }
    // println!("{:?}", char_indices);

    for _ in 0..q {
        let query = input_vec();
        if query[0] == "1" {
            let idx: usize = query[1].parse().unwrap();
            let idx = idx - 1;
            let from_char = s[idx];
            let to_char = query[2].chars().next().unwrap();

            let target_idx = char_indices[from_char as usize - 97].binary_search(&idx).ok().unwrap();
            char_indices[from_char as usize - 97].remove(target_idx);

            s[idx] = to_char;
            let target_idx = char_indices[to_char as usize - 97].binary_search(&idx).err().unwrap();
            char_indices[to_char as usize - 97].insert(target_idx, idx);
        } else {
            let left: i32 = query[1].parse().unwrap();
            let left = left - 1;
            let right: i32 = query[2].parse().unwrap();
            let right = right - 1;
            let mut sum = 0;
            for each_indices in &char_indices {
                if each_indices.len() == 0 {
                    continue;
                }
                let left_idx = binary_search(each_indices.len() as i32, -1, |idx| {
                    each_indices[idx] as i32 >= left
                });

                let right_idx = binary_search(-1, each_indices.len() as i32, |idx| {
                    right >= each_indices[idx] as i32
                });
                // println!("{}, {}", left_idx, right_idx);
                if left_idx <= right_idx {
                    sum += 1;
                }
            }
            println!("{}", sum);
            // println!("{:?}", char_indices);
        }
    }
}


Measured memory_bytes: 16632
#include <iostream>
#include <string>
using namespace std;

int main(){
    int a,b;
    cin>>a>>b;
    int tmp=a,ans=1;
    if(b==1){
        cout<<0<<"\n";
        return 0;
    }
    while(tmp<b){
        tmp+=a;
        tmp--;
        ans++;
    }
    cout<<ans<<"\n";
    return 0;
}


Measured memory_bytes: 256
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun 28 21:08:55 2020

@author: matanoakihiro
"""

import numpy as np

D=int(input())
C=np.array(list(map(int,input().split())))
minus_list=C
S=[]
S_sa=[]
sa=[]
for i in range(D):
    s=np.array(list(map(int,input().split())))
    sa=s-minus_list
    S_sa.append(sa)
    S.append(s)
    sama=max(sa)
    for j in range(26):
        if sama==sa[j]:
            minus_list[j]=0
        
    minus_list+=C
    

for i in range(D):
    A=S_sa[i].tolist()
    ma=max(S_sa[i])
    print(A.index(ma)+1)


Measured memory_bytes: 27484
N=int(input())
if N==0:
    N=0
elif N>0:
    n=format(N,"b")
    for i in range(10**9):
        if i==len(n):
            break
        elif i%2==1:
            if n[-i-1]=="1":
                N+=2**(i+1)
                n=format(N,"b")
else:
    N*=-1
    n=format(N,"b")
    for i in range(10**9):
        if i==len(n):
            break
        elif i%2==0:
            if n[-i-1]=="1":
                N+=2**(i+1)
                n=format(N,"b")
print(int(format(N,"b")))


Measured memory_bytes: 3064
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i = 0; i < (n); ++i)
using ll = long long;
using P = pair<int, int>;

int main(){
  string s;
  cin >> s;

  int count;
  int ans = 0;
  rep(i, s.size()){
    if (s[i] == 'A' || s[i] == 'C' || s[i] == 'G' || s[i] == 'T'){
      count = 0;
      int j = 0;
      while(1){
        if (i + j >= s.size()) break;
        if (s[i+j] == 'A' || s[i+j] == 'C' || s[i+j] == 'G' || s[i+j] == 'T') count++;
        else break;
        if (ans < count) ans = count;
        ++j;
      }
    }
  }
  cout << ans << endl;
  return 0;
}

Measured memory_bytes: 3564
// Do you knOW what it feels like?

		// To be TorTured by your own MinD?
	
	// I don't wanna feel the PAIN.

// I BeG you to KILL me, pleASE...

#include <bits/stdc++.h>
using namespace std;

#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
//#pragma GCC optimize("Os")

#define F first
#define S second
#define pb push_back
#define SZ(x) (ll)(x.size())
#define all(x) x.begin(),x.end()

typedef long long ll;
typedef pair<ll,ll> pll;
typedef long double ld;

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const ll maxn=3e3+10, lg=22, mod=1e9+7, inf=1e18;

ll n,a[maxn];
vector<ll> g[maxn];

bool dfs(ll v,ll pa=0){
	bool F=0;
	for(auto u:g[v])if(u!=pa)if(!dfs(u,v) && a[u]<a[v]) F=1;
	return F;
}

int main(){
	ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0);

	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<n;i++){
		ll v,u; cin>>v>>u;
		g[v].pb(u), g[u].pb(v);
	}
	for(int rt=1;rt<=n;rt++)if(dfs(rt)) cout<<rt<<' ';

	return 0;
}












Measured memory_bytes: 640
#include <bits/stdc++.h>
using namespace std;
#define ll long long int

int power(int x,int n)
{
    if(n==0)
        return 1;
    int result=power(x,n/2);
    if(n&1)
        return x*result*result;
    return result*result;
}
int main()
{
    int n,m,x;
    while(cin>>n>>m>>x)
    {
        int c[n],ara[n][m];
        for(int i=0;i<n;i++)
        {
            cin>>c[i];
            for(int j=0;j<m;j++)cin>>ara[i][j];
        }

        int mn=INT_MAX;
        int q=power(2,n);
        for(int i=1;i<q;i++)
        {
            int mara[m];
            memset(mara,0,sizeof mara);
            int sum=0;
            for(int j=0;j<n;j++)
            {
                 if(i & (1<<j))
                {
                    for(int k=0;k<m;k++)
                    {
                        mara[k]+=ara[j][k];
                    }
                    sum+=c[j];
                }
            }

            bool f=true;
            for(int j=0;j<m;j++)
            {
                if(mara[j]<x)
                {
                    f=false;
                    break;
                }
            }
            if(f)mn=min(mn,sum);
        }
        if(mn==INT_MAX) cout<<"-1"<<endl;
        else cout<<mn<<"\n";
    }
    return 0;
}




Measured memory_bytes: 3616
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner scan = new Scanner(System.in);
        int A = scan.nextInt();
        int B = scan.nextInt();
        int amari = (B-1)%(A-1);
        int ans=0;
        if(amari==0){
             ans=(B-1)/(A-1);
        }else{
            ans=((B-1)+(A-amari))/(A-1);
        }
        System.out.println(ans);
    }
}


Measured memory_bytes: 23764
n,a,b = map(int,input().split())

if (a+b) % 2 == 0:
    print(b - (a+b)//2)
else:
    if a <= n-b+1:
        b -= a
        print(a + b-(1+b)//2)
    else:
        a += n-b+1
        print(n-b+1 + n - (n+a)//2)



Measured memory_bytes: 38384
using System;
using System.Linq;

class Program
{
	static void Main(string[] args)
	{
		var xab = Console.ReadLine().Split().Select(int.Parse).ToArray();
		int x = xab[0], a = xab[1], b = xab[2];
		int n = Math.Abs(x - a), m = Math.Abs(x - b);
		Console.WriteLine(n < m ? "A" : "B");
	}
}

Measured memory_bytes: 13396
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for(ll i=0;i<n;i++)

int main(){
    int a, b;
    cin >> a >> b;
    if(a<=b){
        cout << a << endl;
    }else{
        cout << a-1 << endl;
    }
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <map>
#include <vector>
#include <numeric>

using namespace std;

typedef long long ll;

int main() {
    ios::sync_with_stdio(false);
    ll n;
    cin >> n;
    vector<ll> a(n);
    map<ll, ll> c;
    for (ll i = 0; i < n; ++i) cin >> a.at(i), ++c[a.at(i)];
    ll k = accumulate(c.begin(), c.end(), 0LL, [](ll v, pair<ll, ll> i) {
        return v += i.second * (i.second - 1);
    }) / 2;
    for (ll i = 0; i < n; ++i) cout << k - (c.at(a.at(i)) - 1) << endl;
    return 0;
}


Measured memory_bytes: 11136
#include <algorithm>
#include <iostream>
#include <queue>
#include <string>
#include <map>
using namespace std;

map<string,int> puzzle;

struct state{
	string str;
	int num;
};

int main(void){
	state init;

	init.str="01234567";
	init.num=0;

	queue<state> q;
	q.push(init);

	while(!q.empty()){
		state now=q.front();q.pop();

		string cur=now.str;
		//cout << cur << endl;

		if(puzzle.find(cur)!=puzzle.end())
			continue;

		puzzle[cur]=now.num;

		int i;
		for(i=0;i<8;i++)
			if(cur[i]=='0')
				break;

		int r=i/4;
		int c=i%4;
		
		// row
		if(r){
			state next;
			next.str=cur;
			swap(next.str[i],next.str[i-4]);
			next.num=now.num+1;
			q.push(next);
		}else{
			state next;
			next.str=cur;
			swap(next.str[i],next.str[i+4]);
			next.num=now.num+1;
			q.push(next);
		}
		// column

		if(c!=3){
			state next;
			next.str=cur;
			swap(next.str[i],next.str[i+1]);
			next.num=now.num+1;
			q.push(next);
		}
		if(c!=0){
			state next;
			next.str=cur;
			swap(next.str[i],next.str[i-1]);
			next.num=now.num+1;
			q.push(next);
		}
	}

	while(true){
		int a[8];
		for(int i=0;i<8;i++)
			cin >> a[i];

		if(cin.eof())
			break;
		
		string query;
		for(int i=0;i<8;i++){
			char cur=a[i]+'0';
			query+=cur;
		}
		//cout << query << endl;
		cout << puzzle[query] << endl;
	}
	return 0;
}

Measured memory_bytes: 3540
import Control.Applicative

type Problem = (String, String)

type Result = Bool

solve :: Problem -> Result

solve (s, p)
    = search r p l where
        r = concat $ replicate 2 s
        l = length p
        
search :: String -> String -> Int -> Bool

search s p l
    | length s < l
        = False
        
    | otherwise
        = if all id $ zipWith (==) (take l s) p
            then True
            else search (tail s) p l

output :: Result -> String

output True
    = "Yes"
    
output False
    = "No"
    
input :: IO Problem

input
    = do
        s <- getLine
        p <- getLine
        return (s, p)

main :: IO ()

main
    = putStrLn.output =<< solve <$> input

Measured memory_bytes: 3628
#include <iostream>
#include <cstdio>
using namespace std;
const int N=100000;
long long int a[N],b[N];
int main(){
    int n;
    while(cin>>n){
        for(int i=0;i<n;i++){
            cin>>a[i]>>b[i];
        }
        long long int ans=0;
        long long int temp=0;
        for(int i=n-1;i>=0;i--){
            if((a[i]+temp)%b[i]!=0){
                ans+=b[i]-(a[i]+temp)%b[i];
                temp+=b[i]-(a[i]+temp)%b[i];
            }
        }
        cout<<ans<<endl;
    }
return 0;
}


Measured memory_bytes: 1792
[X,Y] = list(map(int,input().split()))
shokin = 0

if X==1:
    shokin +=300000
elif X==2:
    shokin +=200000
elif X==3:
    shokin +=100000

if Y==1:
    shokin +=300000
    if X==1:
        shokin += 400000
elif Y==2:
    shokin +=200000
elif Y==3:
    shokin +=100000

print(shokin)


Measured memory_bytes: 3060
#include <bits/stdc++.h>
using namespace std;

int H[100005];
bool isGood[100005];

int main()
{
	int N, M;
	scanf("%d%d", &N, &M);
	
	for(int i = 1; i <= N; i++)
	{
		scanf("%d", &H[i]);
		isGood[i] = true;
	}
	
	for(int i = 1; i <= M; i++)
	{
		int Ai, Bi;
		scanf("%d%d", &Ai, &Bi);
		
		if(H[Ai] <= H[Bi])
			isGood[Ai] = false;
		
		if(H[Bi] <= H[Ai])
			isGood[Bi] = false;
	}
	
	int ans = 0;
	for(int i = 1; i <= N; i++)
		ans += isGood[i];
		
	printf("%d", ans);
}

Measured memory_bytes: 4312
#include<iostream>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;

int main(){

	int ans;
	int a , b;

	cin >> a >> b;

	ans = ((a + b) % 2 == 0) ? (a + b) / 2 : (a + b) / 2 + 1;

	cout << ans << endl;
}

Measured memory_bytes: 256
package main

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

const (
	initialBufSize = 100000
	maxBufSize     = 10000000
)

var (
	sc = bufio.NewScanner(os.Stdin)
	wt = bufio.NewWriter(os.Stdout)
)

func next() string {
	sc.Scan()
	return sc.Text()
}

func nextInt() int {
	i, _ := strconv.Atoi(next())
	return i
}

func nextInts(n int) []int {
	slice := make([]int, n)
	for i := 0; i < n; i++ {
		slice[i] = nextInt()
	}
	return slice
}

func nextFloat64() float64 {
	f, _ := strconv.ParseFloat(next(), 64)
	return f
}

func nextFloat64s(n int) []float64 {
	slice := make([]float64, n)
	for i := 0; i < n; i++ {
		slice[i] = nextFloat64()
	}
	return slice
}

func putf(format string, a ...interface{}) {
	fmt.Fprintf(wt, format, a...)
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}

func main() {
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, initialBufSize), maxBufSize)
	defer wt.Flush()

	k := nextInt()

	q := make([]int, 0)
	for i := 1; i <= 9; i++ {
		q = append(q, i)
	}
	for i := 1; i < k; i++ {
		x := q[0]
		if x%10 != 0 {
			q = append(q, 10*x+x%10-1)
		}
		q = append(q, 10*x+x%10)
		if x%10 != 9 {
			q = append(q, 10*x+x%10+1)
		}
		q = q[1:]
	}

	puts(q[0])
}


Measured memory_bytes: 9472
import java.util.*;

public class Main {

    long INF = Long.MAX_VALUE;

    public static void main(String[] args) {
        new Main().solve();
    }

    void solve() {
        Scanner sc = new Scanner(System.in);
        long N = sc.nextLong();
        long A = sc.nextLong();
        long B = sc.nextLong();
        long max=(N-1)*B+A;
        long min=(N-1)*A+B;
        if((N==1&A!=B)||A>B){
            System.out.println("0");
            return;
        }
        System.out.println(max-min+1);
    }
}

Measured memory_bytes: 21844
#include <cstdio>
    #include <algorithm>
    #include <vector>
    #include <bitset>
    using namespace std;
    long long gcd(long long a, long long b) {
    	if (a < b) return gcd(b, a);
    	if (b == 0) return a;
    	return gcd(b, a % b);
    }
    bitset<1000001> bs;
    vector<long long> primes;
    void sieve() {
    	bs.set();
    	bs[0] = bs[1] = 0;
    	for (long long i = 2; i <= 1000000; ++i) {
    		if (bs[i]) {
    			primes.push_back(i);
    			for (long long j = i * i; j <= 1000000; j += i) bs[j] = 0;
    		}
    	}
    }
    int main() {
    	sieve();
    	long long A, B, ans = 1;
    	scanf("%lld %lld", &A, &B);
    	A = gcd(A, B);
    	for (long long i: primes) {
    		if (A % i == 0) ++ans;
    		while (A % i == 0) A /= i;
    	}
    	if (A != 1) ++ans;
    	printf("%lld", ans);
    	return 0;
    }

Measured memory_bytes: 1528
#include <bits/stdc++.h>
using namespace std;
#define rep for(int i = 0;i<n;i++)
#define ll long long
 
//const int INF = 1e8;
const int MOD = 1000000007;
typedef pair<int,int>P;
int dx[4] = {1,0,-1,0};int dy[4] = {0,1,0,-1};
queue<P> que;

int main(){
    bool frag = false;
    int n;cin >> n;
   int a[n+1];int ans = 0;
   for(int i = 1;i<=n;i++) cin >> a[i];
   int b[n+1];for(int i = 1;i<=n;i++){
       b[i] = 0;
   }
   //後ろから考えると決まりやすい
   for(int i = n;i>=1;i--){
       int sum = 0;
       for(int j = 1;i*j<=n;j++){
           sum += b[i*j];
       }
       if(i == n){
            b[i] = a[i];
            if(a[i]== 1) ans += 1;
       }else{
           if(sum == 0){
               b[i] = a[i];
               if(a[i]== 1) ans += 1;
           }else if(sum % 2 == a[i]){
               b[i] = 0;
           }else{
               b[i] = 1;
               ans += 1;
           }
       }
   }
   //出力 0の時一致できるかどうかで決める
    if(frag == true){
        cout << -1 << endl;
    }else{
        cout  << ans << endl;
        for(int i = 1;i<=n;i++){
            if(b[i]==1) cout << i << " ";
        }
        if(ans >0)cout << endl;
    }

}

Measured memory_bytes: 2432
#include<iostream>
#include<vector>
using namespace std;
int main() {
  int N;
  long long K;
  cin >> N >> K;
  vector<int> A(N);
  long long i;
  for(i=0;i<N;i++)cin >> A[i];
  vector<int> P(N,-2);
  P[0] = -1;
  int pos = 0;
  bool f = false;
  for(i=0;i<K;i++) {
    pos = A[pos]-1;
    if(!f) {
      if(P[pos] < -1)P[pos] = i;
      else {
        int llen = i - P[pos];
        K = (K-i-1)%llen + i+1;
        f = true;
      }
    }
  }
  cout << pos+1 << endl;
}

Measured memory_bytes: 4844
"""
回文の左半分の文字列たちを操作する。
左半分の各文字に対して、本来あるべき場所(Index)を定義する。
あとは、左半分の文字

"""

from collections import Counter
class BIT:
    def __init__(self, n):
        self.size = n
        self.tree = [0] * (n + 1)

    def sum(self, i):  # 1-index
        s = 0
        while i > 0:
            s += self.tree[i]
            i -= i & -i
        return s

    def add(self, i, x):  # 1-index
        while i <= self.size:
            self.tree[i] += x
            i += i & -i

S = input()
N = len(S)
count = Counter(S)

#奇数個ある文字が複数存在していないかチェック
flag = False
for v in count.values():
    if v%2 == 1:
        if flag:
            print(-1)
            exit()
        else:
            flag = True

# 各文字が属すべきインデックスを求める
# memo[i] -> S[i]の回文変換後のインデックス(0-indexed)
memo = [None]*(N)
#appearCnt[k] -> 文字kの出現回数
appearCnt = {k:0 for k in count.keys()}

# まず、回文時に左半分に属する文字に関して、インデックスを割り当てる。
tInd = 0
for i in range(N):
    s = S[i]
    if appearCnt[s] <= count[s]//2 - 1:
        appearCnt[s] += 1
        memo[i] = tInd
        tInd += 1

#奇数個ある文字がある場合は、真ん中になる文字に関して、インデックスを割り当てる
if flag:
    for i in range(N):
        s = S[i]
        if count[s]%2 == 1 and memo[i]==None:
            memo[i] = tInd
            break

#回文時に右半分になる文字にインデックスを割り当てる。
#まず、各文字の文字列Sにおける出現回数をまとめる
appearIdx = {k:[] for k in count.keys()}
for i in range(N):
    s = S[i]
    appearIdx[s].append(i)

for v in appearIdx.values():
    for i in range(len(v)//2):
        l = v[i]
        r = v[len(v)-i-1]
        memo[r] = (N-1)-memo[l]
ans = 0
bit = BIT(N)
for i in range(N):
    bit.add(memo[i]+1,1)
    ans += bit.sum(N)-bit.sum(memo[i]+1)
print(ans)



Measured memory_bytes: 97316
s = input()
K = int(input())
n = len(s)
A =[]
import bisect
for i in range(n):
    for j in range(1,K+1):
        sub = s[i:i+j]  
        if sub not in A:
            x = bisect.bisect_left(A,sub)
            A.insert(x,sub)
            if len(A) > K:
                A.pop(K)

print(A[K-1])

Measured memory_bytes: 3064
// https://atcoder.jp/contests/abc074/tasks/arc083_b
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define REP(i, n) FOR(i, 0, n)
#define FOR(i, s, n) for (int i = (s), i##_len = (n); i < i##_len; ++i)
#define ALL(obj) (obj).begin(), (obj).end()
#define ALLR(obj) (obj).rbegin(), (obj).rend()

int main() {
    int n;
    cin >> n;
    vector<vector<int>> d(n, vector<int>(n));
    vector<vector<bool>> b(n, vector<bool>(n));

    REP(i, n) REP(j, n) cin >> d[i][j];
    REP(k, n) REP(i, n) {
        if (k == i)
            continue;
        REP(j, n) {
            if (k == j)
                continue;
            // 3辺の一番長い辺が、それ以外の辺の合計より大きければ不成立
            if (d[i][j] > d[i][k] + d[k][j]) {
                cout << "-1\n";
                return 0;
            }
            // 等しければ辺を作らない
            if (d[i][j] == d[i][k] + d[k][j]) {
                b[i][j] = true;
            }
        }
    }
    ll ans = 0;
    REP(i, n) FOR(j, i + 1, n) {
        if (!b[i][j]) {
            ans += d[i][j];
        }
    }
    cout << ans << endl;

    return 0;
}


Measured memory_bytes: 640
#define debug(x) cout<<#x<<": "<<x<<endl
#define rep(a, b) for(int unsafe_cnt=a; unsafe_cnt < b;unsafe_cnt++)
#define fn auto
#include <iostream>
#include <stdio.h>
#include <vector>
#include <math.h>
#include <algorithm>
#include <string>
using namespace std;

void newline() {cout << endl;}
template <typename T> void display(T input){cout << input;}
template <typename T> void put(T input){display(input); newline();}
void iput(int input) {put(input);}

fn main() -> int {
  char a, b;
  cin >> a >> b;
  if(a == 'H'){
    if(b == 'H'){
        put('H');
    }else{
        put('D');
    }
  }else{
    if(b == 'H'){
        put('D');
    }else{
        put('H');
    }
  }
}

Measured memory_bytes: 256
//Optimize
#pragma GCC optimize("Ofast")

//Head File
#include<bits/stdc++.h>
using namespace std;

#define il inline

//Variable
#define ll long long
#define ull unsigned long long
#define db double
#define lb long double
#define ui unsigned int

//Debug
#define B cerr<<"Break Point"<<endl;
#define P(x) cerr<<#x<<' '<<"="<<' '<<(x)<<endl;
#define p(x) cerr<<#x<<' '<<"="<<' '<<(x)<<' ';
#define ml(x) cerr<<"Size of array is "<<x*4/1024/1024<<" MB"<<endl;

//Vector
#define vc vector
#define puf push_front
#define pof pop_front
#define pub push_back
#define pob pop_back
#define vbe(x) x.begin(),x.end()

//Memset
#define ms(x) memset(x,0,sizeof(x))
#define MS(x) memset(x,0x3f3f3f3f,sizeof(x))

//Pair
#define fi first
#define se second

//File

#define fin(x) freopen(x,"r",stdin)
#define fou(x) freopen(x,"w",stdout)
void fio()
{
    #ifndef ONLINE_JUDGE
    freopen("sample.in","r",stdin);
    freopen("sample.out","w",stdout);
    #endif
}
void pti()
{
    double timeuse = clock()*1000.0/CLOCKS_PER_SEC;
    cerr<<"Timeuse "<<timeuse<<"ms"<<endl;
}
void end()
{
    pti();
    exit(0);
}

//Inf
#define INF 0x3f3f3f3f
#define LINF ((long long)(0x3f3f3f3f3f3f3f3f))

//IO
#define pc(s) putchar(s)
#define say(s) cout<<s<<endl
namespace io
{
    const int SIZ=55;int que[SIZ],op,qr;char ch;
    template<class I>
    il void gi(I &w)
    {
        ch=getchar(),op=1,w=0;while(!isdigit(ch)){if(ch=='-') op=-1;ch=getchar();}
        while(isdigit(ch)){w=w*10+ch-'0';ch=getchar();}w*=op;
    }
    template<class I>
    il void print(I w)
    {
        qr=0;if(!w) putchar('0');if(w<0) putchar('-'),w=-w;while(w) que[++qr]=w%10+'0',w/=10;
        while(qr) putchar(que[qr--]);
    }
}
using io::gi;
using io::print;

const int N=2e5+5;

ll n,cnta,cntb,cntc,num,k;
ll a[N],b[N],c[N];

int find(int l,int r,ll s,ll d,ll *x)
{
    int pos=l-1;
    while(l<=r)
    {
        int mid=(l+r)>>1;
        if(x[mid]*s>=d) l=mid+1,pos=mid;
        else r=mid-1;
    }
    return pos;
}
bool check(ll v)
{
    ll res=0;
    for(int i=1;i<=cnta;++i)
    {
        int pos=find(i+1,cnta,a[i],v,a);
        res+=pos-i;
    }
    if(v<=0) res+=num*cnta+num*cntb+num*(num-1)/2;
    for(int i=1;i<=cntb;++i)
    {
        int pos=find(i+1,cntb,b[i],v,b);
        res+=pos-i;
    }
    for(int i=1;i<=cnta;++i)
    {
        int pos=find(1,cntc,a[i],v,c);
        res+=pos;
    }
    res=n*(n-1)/2-res;
    if(res<k) return true;
    else return false;
}
int main()
{
    gi(n),gi(k);
    for(int i=1;i<=n;++i) 
    {
        ll x;
        gi(x);
        if(x>0) a[++cnta]=x;
        else if(x<0) b[++cntb]=x,c[++cntc]=x;
        else ++num;
    }
    sort(a+1,a+cnta+1,[](ll x,ll y){
        return x>y;
    });
    sort(b+1,b+cntb+1,[](ll x,ll y){
        return x<y;
    });
    sort(c+1,c+cntc+1,[](ll x,ll y){
        return x>y;
    });
    ll l=-1e18-1,r=1e18+1,ans;
    while(l<=r)
    {
        ll mid=(l+r)>>1;
        if(check(mid)) l=mid+1,ans=mid;
        else r=mid-1;
    }
    print(ans);
    end();
}


Measured memory_bytes: 4096
using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication9
{
    class Program
    {
        static void Main(string[] args)
        {



            int n = int.Parse(Console.ReadLine());
            String[] str = Console.ReadLine().Split(' ');
            int[] a = new int[n];

            for(int i=0;i<n;i++ ){
                a[i] =int.Parse(str[i]);
            }

            for (int i = n-1; i >= 0; i--)
            {
                if (i > 0)
                {
                    Console.Write(a[i] + " ");
                }
                if (i == 0)
                {
                    Console.Write(a[i]);
                }
            }
            Console.WriteLine();
            

        }
    }
}

Measured memory_bytes: 19956
#include <bits/stdc++.h>
#include <iomanip>
using namespace std;
#define reps(i,s,n) for(int i = s; i < n; i++)
#define rep(i,n) reps(i,0,n)
#define Rreps(i,n,e) for(int i = n - 1; i >= e; --i)
#define Rrep(i,n) Rreps(i,n,0)
#define ALL(a) a.begin(), a.end()
#define fi first
#define se second
typedef long long ll;
typedef vector<ll> vec;
typedef vector<vec> mat;

ll N,M,H,W,K,Q,A,B;
string S;
const ll MOD = 998244353;
//const ll MOD = (1e+9) + 7;
const ll INF = 1LL<<60;
typedef pair<ll, ll> P;

int main() {
    ll X, Y, C;
    cin>>X>>Y>>A>>B>>C;
    vec p(A), q(B), r(C);
    rep(i,A) cin>>p[i];
    rep(i,B) cin>>q[i];
    rep(i,C) cin>>r[i];
    ll ans = 0;
    sort(ALL(p));
    reverse(ALL(p));
    sort(ALL(q));
    reverse(ALL(q));
    sort(ALL(r));
    reverse(ALL(r));
    priority_queue<ll, vector<ll>, greater<ll>> pque;
    rep(i,X){
        ans += p[i];
        pque.push(p[i]);
    }
    rep(i,Y){
        ans += q[i];
        pque.push(q[i]);
    }
    int id = 0;
    while(!pque.empty() && id != C){
        ll m = pque.top();
        pque.pop();
        if(m >= r[id]) break;
        ans += r[id] - m;
        ++id;
    }
    cout<<ans<<endl;
}

Measured memory_bytes: 4852
#include <bits/stdc++.h>
using namespace std;

long long x, n, cnt[100010], ans, m;

int main () {
	cin>>n;
	
	for(int i=1; i<=n; i++){
		cin>>x;
		cnt[x-1]++;
		cnt[x]++;
		cnt[x+1]++;
		m=max(m, x);
	}
	
	for(int i=-1; i<=m+1; i++){
		if(cnt[i]>ans) ans=cnt[i];
	}
	cout<<ans<<endl;
}

Measured memory_bytes: 4268
#include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<(int)(n);i++)
#define all(v) v.begin(),v.end()
#define rall(v) v.rbegin(),v.rend()
typedef long long ll;
#define _GLIBCXX_DEBUG
typedef vector<int> vec;
typedef vector<ll> lvec;
typedef vector<char>cvec;
typedef pair<ll, ll> LP;
typedef tuple<ll, ll, ll> LT;
typedef pair<int, int> P;
typedef tuple<int, int, int> T;
int main()	{
  int n,ans=0;
  cin>>n;
  vector<int>h(n);
  rep(i,n) cin>>h[i];
  int cnt=0;
  rep(i,n-1){
    if(h[i]>=h[i+1]){
      cnt++;
    }
    else{
      ans=max(cnt,ans);
      cnt=0;
    }
  }
  ans=max(cnt,ans);
  cout<<ans<<endl;
}

Measured memory_bytes: 640
#include <iostream>

using namespace std;

//#define int long long

using ll = long long;
using pii =  pair<int, int>;

const int IINF =  0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3fLL;
const int INF = sizeof(int) == sizeof(long long) ? LINF : IINF;
const ll MOD = 1e9+7;

#define for_(i, a, b) for(int i = (a);i < (b);++i)
#define rfor_(i, a, b) for(int i = (b)-1;i >= (a);--i)

#define rep(i, n) for_(i, 0, n)
#define rrep(i, n) rfor_(i, 0, n)

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define ft first
#define sd second

#define all(a) (a).begin(), (a).end()
#define sz(a) (int)(a).size()
#define rev(a) reverse(all(a))

#define endl '\n'

const int limit = 100007;

ll N;

signed main() {
  cin.tie(0);cout.tie(0);
  ios_base::sync_with_stdio(false);

  cin >> N;

  ll sum = 0;

  for(ll k=1;(k*k+k)<N;++k) {
    if( N % k == 0 ) sum += (N-k)/k;
  }

  cout << sum << endl;

  return 0;
}


Measured memory_bytes: 888
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX 10000000

int min(int a, int b) {
	return a < b ? a : b;
}

int min_cost(int *height, int n, int i, int *dp) {
	if (i == n-1) return 0;
	if (i >= n) return MAX;

	if (dp[i] != -1) return dp[i];

	int one_step = abs(height[i] - height[i+1]) + min_cost(height, n, i+1, dp);
	int two_step = abs(height[i] - height[i+2]) + min_cost(height, n, i+2, dp);
	dp[i] = min(one_step, two_step);
	return dp[i];
}

int main() {
	int n, i;
	scanf("%d", &n);

	int height[n], dp[n];
	memset(dp, -1, n*sizeof(int));
	for (i = 0; i < n; i++) scanf("%d", &height[i]);

	printf("%d\n", min_cost(height, n, 0, dp));
	return 0;
}

Measured memory_bytes: 8704
#include <bits/stdc++.h>
using namespace std;

#ifdef LOCAL
#include "debug.h"
#else
#define DEBUG(...)
#endif

int main() {
  cin.tie(nullptr);
  ios::sync_with_stdio(false);
  string s, t;
  cin >> s >> t;
  int n = size(s), res = 0;
  for (int i = 0; i < n; ++i) {
    res += s[i] != t[i];
  }
  cout << res << '\n';
}


Measured memory_bytes: 3848
using System;
using System.Collections.Generic;
using System.Windows;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Atcoder
{
    public class Program
    {
        static void Main(string[] args)
        {
            var n = Read().ToInt32();
            var h = new long[100010];
            var dp = new long[100010];
            var r = ReadSplit();
            var INF = 9999999999999;
            for (int i = 0; i < n; i++)
            {
                h[i] = r[i].ToInt64();
            }

            for (int i = 0; i < 100010; i++)
            {
                dp[i] = INF;
            }

            dp[0] = 0;

            for (int i = 1; i < n; i++)
            {
                if(dp[i] > dp[i - 1] + Math.Abs(h[i] - h[i - 1]))
                {
                    dp[i] = dp[i - 1] + Math.Abs(h[i] - h[i - 1]);
                }

                if (i > 1)
                {
                    if (dp[i] > dp[i - 2] + Math.Abs(h[i] - h[i - 2]))
                    {
                        dp[i] = dp[i - 2] + Math.Abs(h[i] - h[i - 2]);
                    }
                }
            }

            var ans = dp[n - 1];
            WriteRead(ans);
        }

        public static string Read()
        {
            return Console.ReadLine();
        }

        public static string[] ReadSplit()
        {
            return Console.ReadLine().Split(' ');
        }

        public static void WriteRead(object str)
        {
            Console.WriteLine(str);
            Read();
        }

        public static void Write(object str)
        {
            Console.WriteLine(str);
        }
    }
}


public static class Extentions
{
    public static int ToInt32(this object obj)
    {
        return int.Parse(obj.ToString());
    }

    public static long ToInt64(this object obj)
    {
        return long.Parse(obj.ToString());
    }

    public static decimal ToDecimal(this object obj)
    {
        return decimal.Parse(obj.ToString());
    }

    public static double ToDouble(this object obj)
    {
        return double.Parse(obj.ToString());
    }

    public static T2 GetValueZero<T1, T2>(this Dictionary<T1, T2> d, T1 key) where T2 : struct
    {
        T2 value;
        if (d.TryGetValue(key, out value))


        {
            return value;
        }
        return new T2();
    }
}



Measured memory_bytes: 17632
n = int(input())
l = list(map(int,input().split()))

num = max(l)+1
rcd = [0 for _ in range(num)]

for v in l:
    rcd[v] += 1

unq = []
for w in range(num):
    if rcd[w] == 1:
        unq.append(w)
#print(unq)

rcd = [0 for _ in range(num)]
l = set(l)
for x in l:
    for y in range(2*x, num, x):
        rcd[y] = 1
#print(rcd)

ans = 0
for z in unq:
    if rcd[z] == 0:
        ans += 1
print(ans)


Measured memory_bytes: 47448
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
typedef pair<int, int> pi;

#define rep(i, n) for (int i = 0; i < n; i++)
#define rep_op(i, a, n) for (int i = a; i < n; i++)
#define rep_d(j, n) for (int j = n; j >= 0; j--)
#define rep_d_op(j, n, a) for (int j = n; j >= a; j--)

template <class T>
inline bool chmax(T &a, T b)
{
    if (a < b)
    {
        a = b;
        return 1;
    }
    return 0;
}
template <class T>
inline bool chmin(T &a, T b)
{
    if (a > b)
    {
        a = b;
        return 1;
    }
    return 0;
}

const int MOD = 1000000007;

const vector<int> dx = {1, 0};
const vector<int> dy = {0, 1};
const ll INF = 1LL << 60;

// int max = *std::max_element(vec.begin(), vec.end());
// int sum = accumulate(list, list + size, 0);

int calc(int a, int b, int c)
{
    if (a % 2 == 1 || b % 2 == 1 || c % 2 == 1)
    {
        return 0;
    }
    if (a == b && a == c)
    {
        return -1;
    }
    return calc((b + c) / 2, (c + a) / 2, (a + b) / 2) + 1;
}

int main()
{
    int a, b, c;
    cin >> a >> b >> c;
    int ans = calc(a, b, c);
    cout << ans << endl;
}


Measured memory_bytes: 256
#include <iostream>
#include <complex>
#include <sstream>
#include <string>
#include <algorithm>
#include <deque>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <vector>
#include <set>
#include <limits>
#include <cstdio>
#include <cctype>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <ctime>
using namespace std;
#define REP(i, j) for(int i = 0; i < (int)(j); ++i)
#define FOR(i, j, k) for(int i = (int)(j); i < (int)(k); ++i)
#define SORT(v) sort((v).begin(), (v).end())
#define REVERSE(v) reverse((v).begin(), (v).end())
typedef pair<int, vector<int> > P;
const int INF = 1e9;

int N, M, a, b;
vector<int> v, d;
set< vector<int> > S;
queue<P> open;

bool solve(vector<int> &vec){
  vector<int> tmp;
  int cnt = 1;
  FOR(i, 1, vec.size()){
    if(vec[i] == vec[i - 1]) ++cnt;
    else{
      tmp.push_back(cnt);
      cnt = 1;
    }
  }
  tmp.push_back(cnt);
  if(M != (int)(tmp.size())) return false;
  REP(i, M) if(tmp[i] != d[i]) return false;
  return true;
}

int main() {
  cin >>N >>M;
  int n = 0;
  d = vector<int>(M);
  vector<int> v(N);
  REP(i, N) cin >>v[i];
  REP(i, M) cin >>d[i];
  open.push( P(0, v) );
  while(!open.empty()){
    P tmp = open.front(); open.pop();
    int cnt = tmp.first;
    vector<int> vec = tmp.second;
    if(solve(vec)){
      cout <<cnt <<endl;
      break;
    }
    if(S.find(vec) != S.end()) continue;
    S.insert(vec);
    FOR(i, 1, vec.size()){
      if(vec[i] == vec[i - 1]) continue;
      swap(vec[i], vec[i - 1]);
      open.push( P(cnt + 1, vec) );
      swap(vec[i], vec[i - 1]);
    }
  }
  return 0;
}

Measured memory_bytes: 2332
s=input()
if s.replace("A","")=="KIHBR":
    if "AA"not in s:
        if s[s.index("K")+1]=="A"or s[s.index("I")+1]=="A":
            print("NO")
        else:
            print("YES")
    else:
        print("NO")
else:
    print("NO")

Measured memory_bytes: 3060
#include "bits/stdc++.h"

using namespace std;

using ll = long long;
using ld = long double;
using P = pair<string, int>;
constexpr ld EPS = 1e-12;
constexpr int INF = numeric_limits<int>::max() / 2;
constexpr int MOD = 1e9 + 7;

template <typename T>
void printv(const vector<T> &v)
{
    int sz = v.size();
    for (int i = 0; i < sz; i++)
    {
        cout << v[i] << " \n"[i == sz - 1];
    }
}

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

    vector<ll> res(50);
    res[0] = res[1] = 1;
    for (int i = 2; i <= 44; i++)
        res[i] = res[i - 1] + res[i - 2];
    int n;
    cin >> n;
    cout << res[n] << endl;
}



Measured memory_bytes: 3172
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <regex>
#include <set>
#include <cmath>
#include <sstream>
#include <numeric>
#include <set>

using namespace std;

int main()
{
    int x, y;
    std::cin >> x >> y;
    std::cout << x + y / 2;

    return EXIT_SUCCESS;
}


Measured memory_bytes: 256
S = input()
count_more = 0
count_less = 0
ans = 0
pre_si = '>'
for i, si in enumerate(S):
    if pre_si == '>' and si == '<':
        max_n = max(count_more, count_less)
        min_n = min(count_more, count_less)
        ans += (max_n+1)*(max_n)//2
        # print(i, ans)
        ans += (min_n)*(min_n-1)//2
        count_more = 0
        count_less = 0
        # print(i, ans)
    if si == '<':
        count_more += 1
    elif si == '>':
        count_less += 1
    pre_si = si
max_n = max(count_more, count_less)
min_n = min(count_more, count_less)
ans += (max_n+1)*(max_n)//2
ans += (min_n)*(min_n-1)//2
print(ans)        


Measured memory_bytes: 74404
#include <bits/stdc++.h>
using namespace std;

int main() {
 
  string N;
  cin >> N;

  set<char> st1;
  set<char> st2;

  st1.insert(N[0]);
  st1.insert(N[1]);
  st1.insert(N[2]);

  st2.insert(N[1]);
  st2.insert(N[2]);
  st2.insert(N[3]);

  if (st1.size() == 1 || st2.size() == 1) {
    cout << "Yes" << endl;
  } else {
    cout << "No" << endl;
  }

}

Measured memory_bytes: 256
N,K=map(int,input().split())
a=list(map(int,input().split()))
ans=[0 for e in range(K+1)]
for i in range(a[0]):
 ans[i]=1
for m in range(a[0],K+1):
 t=0
 for j in a:
  if j>m:
   continue
  else:
   if ans[m-j]==1:
    t+=1
 if t==0:
  ans[m]=1
 else:
  ans[m]=0
if ans[K]==0:
 print("First")
else:
 print("Second")


Measured memory_bytes: 44912
#include <iostream>

using namespace std;

int main(int argc, char const *argv[])
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    string s, t;
    cin >> s >> t;
    puts(s.compare(t.substr(0, s.length())) ? "No" : "Yes");

    return 0;
}


Measured memory_bytes: 3104
# -*- coding: utf-8 -*-

from bisect import bisect_left

s = input()
t = input()

if not set(t) <= set(s):
    print(-1)
    exit()

s_dict = {}
for i in range(len(s)):
    c = s[i]
    if c not in s_dict.keys():
        s_dict[c] = [i]
    else:
        s_dict[c].append(i)

repeat = 0
s_idx = 0
for c in t:
    idx = bisect_left(s_dict[c], s_idx)
    if idx == len(s_dict[c]):
        s_idx = s_dict[c][0] + 1
        repeat += 1
    else:
        s_idx = s_dict[c][idx] + 1
else:
    ans = repeat * len(s) + s_idx

print(ans)


Measured memory_bytes: 52336
N, K = gets.split.map(&:to_i)
A = gets.split.map(&:to_i)

remainStepCnt = K

last_visited_at = Hash.new
time = 0
cur = 1

while remainStepCnt > 0
  if last_visited_at[cur]
    len = time - last_visited_at[cur]
    remainStepCnt %= len
  else
    last_visited_at[cur] = time
  end

  if remainStepCnt > 0
    cur = A[cur - 1]
    time += 1
    remainStepCnt -= 1
  end
end

puts cur


Measured memory_bytes: 36888
#include <bits/stdc++.h>
#define repi(i, a, b) for (int i = (int)(a) ; i < (int)(b) ; i++)
#define rep(i, n) repi(i, 0, n)
#define SZ(x) ((int)(x).size())
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
struct Vec{
    double x, y;
};
template<class T> inline bool chmin(T& a, T b) {
    if (a > b) {
        a = b;
        return true;
    }
    return false;
}
template<class T> inline bool chmax(T& a, T b) {
    if (a < b) {
        a = b;
        return true;
    }
     return false;
}
template<class T>
T min(T a, T b)
{
    if (a < b) return a;
    return b;
}
template<class T>
T max(T a, T b)
{
    if (a > b) return a;
    return b;
}
using namespace std;
int main()
{
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    // cout << fixed << setprecision(15);
    int n, k;
    cin >> n >> k;
    vector<ll> a(n);
    rep(i, n) cin >> a[i];
    ll l = 0, r = 1e9;
    while (r - l > 1){
        ll x = (r + l) / 2;
        bool ok = [&]{
            ll ans = 0;
            rep(i, n){
                ans += (a[i] - 1) / x;
            }
            return ans <= k;
        }();
        if (ok) r = x;
        else l = x;
    }
    cout << r << endl;
    return 0;
}

Measured memory_bytes: 4784
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAXN = (int) (2e5 + 10);
char s[MAXN];
int n;
int nxt[26][MAXN];
int dp[MAXN];
string ans;

int main() {
    scanf("%s", s);
    n = (int) strlen(s);
    for (int i = 0; i < 26; i++) {
        nxt[i][n] = n;
    }
    for (int j = 0; j < 26; j++) {
        for (int i = n - 1; i >= 0; i--) {
            nxt[j][i] = nxt[j][i + 1];
            if (s[i] - 'a' == j) {
                nxt[j][i] = i;
            }
        }
    }

    for (int i = n - 1; i >= 0; i--) {
        int mx = -1;
        for (int j = 0; j < 26; j++) {
            mx = max(mx, nxt[j][i]);
        }
        if (mx == n) {
            dp[i] = 0;
        } else {
            dp[i] = dp[mx + 1] + 1;
        }
    }

    string ans = "";
    int len = dp[0];
    int ind = 0;
    while (true) {
        for (int c = 0; c < 26; c++) {
            if (nxt[c][ind] == n || dp[nxt[c][ind] + 1] == len - 1) {
                ans.push_back((char) ('a' + c));
                ind = nxt[c][ind] + 1;
                len--;
                break;
            }
        }
        if (ind >= n) {
            break;
        }
    }

    cout << ans << endl;

    return 0;
}

Measured memory_bytes: 21504
import java.util.*;

public class Main {
    int h, w, n;
    int sh, sw;
    char[] sArr, tArr;

    void run() {
        Scanner sc = new Scanner(System.in);

        h = sc.nextInt();
        w = sc.nextInt();
        n = sc.nextInt();

        sh = sc.nextInt();
        sw = sc.nextInt();

        sArr = sc.next().toCharArray();
        tArr = sc.next().toCharArray();

        boolean isOchiru = rOchiru() || lOchiru() || dOchiru() || uOchiru();


        System.out.println(isOchiru ? "NO" : "YES");
    }

    boolean rOchiru() {
        int w1 = sw;
        for (int i = 0; i < n; i++) {
            if (sArr[i] == 'R') w1++;
            if (w1 > w) {
                return true;
            }
            if (tArr[i] == 'L' && w1 > 1) w1--;
        }
        return false;
    }

    boolean lOchiru() {
        int w1 = sw;
        for (int i = 0; i < n; i++) {
            if (sArr[i] == 'L') w1--;
            if (w1 < 1) {
                return true;
            }
            if (tArr[i] == 'R' && w1 < w) w1++;
        }
        return false;
    }

    boolean dOchiru() {
        int h1 = sh;
        for (int i = 0; i < n; i++) {
            if (sArr[i] == 'D') h1++;
            if (h1 > h) {
                return true;
            }
            if (tArr[i] == 'U' && h1 > 1) h1--;
        }
        return false;
    }

    boolean uOchiru() {
        int h1 = sh;
        for (int i = 0; i < n; i++) {
            if (sArr[i] == 'U') h1--;
            if (h1 < 1) {
                return true;
            }
            if (tArr[i] == 'D' && h1 < h) h1++;
        }
        return false;
    }



    void debug(Object... os) {
        System.err.println(Arrays.deepToString(os));
    }

    public static void main(String[] args) {
        new Main().run();
    }
}


Measured memory_bytes: 29260
#include<iostream>
#include<cmath>
#define loop(i,a,b) for(int i=a;i<b;i++)
#define rep(i,a) loop(i,0,a)
using namespace std;

int main(){
	int n,x,y,b,p;
	cin>>n;
	rep(i,n){
		cin>>x>>y>>b>>p;
		int ans=x*b+y*p;
		if(b>=5 && p>=2){
			ans=ans*0.8;
		}else if(b>=5){
			ans=min(ans,(x*b+y*(p/2+1)*2)*4/5);
		}else if(p>=2){
			ans=min(ans,(x*(b/5+1)*5+y*p)*4/5);
		}
		ans=(int)min(ans,((x*(b/5+1)*5+y*(p/2+1)*2)*4/5));
		cout<<ans<<endl;
	}
	return 0;
}

Measured memory_bytes: 1164