akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>
using namespace std;

typedef long long ll;

int diff_check(string S) {
    int change_to01 = 0;
    int change_to10 = 0;
    for (int i = 0; i < S.size(); i++) {
        if (i % 2 == 0) {
            if (S[i] == '0') change_to10++;
            else if (S[i] == '1') change_to01++;
        }
        else if (i % 2 != 0) {
            if (S[i] == '1') change_to10++;
            else if (S[i] == '0') change_to01++;
        }
    }

    return min(change_to01,change_to10);
}


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

cout << diff_check(S) << endl;

}

Measured memory_bytes: 512
x = int(input())
a = x // 100
b = x % 100

a_is_month = 0 < a & a <= 12
b_is_month = 0 < b & b <= 12

if a_is_month:
    if b_is_month:
        print("AMBIGUOUS")
    else:
        print("MMYY")
else:
    if b_is_month:
        print("YYMM")
    else:
        print("NA")



Measured memory_bytes: 61264
#include<iostream>                                                                                  
#include<stdio.h>                                                                                   
using namespace std;                                                                                
int main(){                                                                                         
  int a, b;                                                                                         
  cin >> a >> b;                                                                                    
  cout << (a/b) << " " << (a%b) << " ";                                                             
  cout << fixed << (double)a / b << endl;                                                           
}                                                                                                   
                                                                                                    
              


Measured memory_bytes: 3276
#include <algorithm>
#include <cstdio>
#define rg register
#define file(x) freopen(x".in", "r", stdin), freopen(x".out", "w", stdout)
using namespace std;
template < class T > inline void read(T& s) {
	s = 0; int f = 0; char c = getchar();
	while ('0' > c || c > '9') f |= c == '-', c = getchar();
	while ('0' <= c && c <= '9') s = s * 10 + c - 48, c = getchar();
	s = f ? -s : s;
}

typedef long long LL;
const int _ = 1e5 + 5;

int n, a[_], t[_], tmp[_]; LL ans;

inline void merge(int l, int r) {
	if (l == r) return ;
	int mid = (l + r) >> 1;
	merge(l, mid), merge(mid + 1, r);
	int i = l, j = mid + 1, p = l;
	while (i <= mid && j <= r) {
		if (t[i] < t[j]) {
			ans += mid - i + 1;
			tmp[p] = t[j], ++p, ++j;
		} else
			tmp[p] = t[i], ++p, ++i;
	}
	while (i <= mid) tmp[p] = t[i], ++p, ++i;
	while (j <= r) tmp[p] = t[j], ++p, ++j;
	for (rg int x = l; x <= r; ++x) t[x] = tmp[x];
}

inline bool check(int mid) {
	t[0] = 0;
	for (rg int i = 1; i <= n; ++i)
		t[i] = t[i - 1] + (a[i] <= mid ? 1 : -1);
	ans = 0, merge(0, n);
	return ans >= (LL) n * (n + 1) / 2 / 2 + 1;
}

int main() {
	read(n);
	int l = 1e9, r = 1;
	for (rg int i = 1; i <= n; ++i) read(a[i]), r = max(r, a[i]), l = min(l, a[i]);
	while (l < r) {
		int mid = (l + r) >> 1;
		if (check(mid)) r = mid; else l = mid + 1;
	}
	printf("%d\n", l);
	return 0;
}


Measured memory_bytes: 1280
class LazySegmentTreeBase
  def initialize(arr, l = 0, r = arr.size - 1)
    @l, @r = l, r
    @lazy = nil
    if l == r
      @agg = arr[l]
    else
      c = (l + r) / 2
      @left_child = self.class.new(arr, l, c)
      @right_child = self.class.new(arr, c + 1, r)
      @agg = aggregation_of(@left_child.agg, @right_child.agg)
    end
  end

  attr_reader :agg, :l, :r

  def update(l, r, x)
    if l == @l && r == @r
      defer(x)
    else
      force
      if r <= @left_child.r
        @left_child.update(l, r, x)
      elsif @right_child.l <= l
        @right_child.update(l, r, x)
      else
        @left_child.update(l, @left_child.r, x)
        @right_child.update(@right_child.l, r, x)
      end
      @left_child.force
      @right_child.force
      @agg = aggregation_of(@left_child.agg, @right_child.agg)
    end
  end

  def force
    return if !@lazy
    x = @lazy
    @lazy = nil
    whole_update(x)
    @left_child.update(@left_child.l, @left_child.r, x) if @left_child
    @right_child.update(@right_child.l, @right_child.r, x) if @right_child
  end

  def query(l, r)
    force
    return @agg if l == @l && r == @r
    if r <= @left_child.r
      return @left_child.query(l, r)
    elsif @right_child.l <= l
      return @right_child.query(l, r)
    else
      agg_left = @left_child.query(l, @left_child.r)
      agg_right = @right_child.query(@right_child.l, r)
      return aggregation_of(agg_left, agg_right)
    end
  end
end

class LazySegmentTree < LazySegmentTreeBase
  def initialize(arr, l = 0, r = arr.size - 1)
    @n = r - l + 1
    super(arr, l, r)
  end

  def defer(x)
    if @lazy
      @lazy += x
    else
      @lazy = x
    end
  end

  def whole_update(x)
    @agg += x * @n
  end

  def aggregation_of(x, y)
    x + y
  end
end

n, q = gets.split.map(&:to_i)
seg = LazySegmentTree.new(Array.new(n, 0))
q.times do
  c, x, y, z = gets.split.map(&:to_i)
  if c == 0
    seg.update(x - 1, y - 1, z)
  else
    puts seg.query(x - 1, x - 1)
  end
end


Measured memory_bytes: 34920
#include<iostream>
#include<algorithm>
using namespace std;int*t,n,m,d,i,s[99999];main(){for(;cin>>d>>n>>m,s[i=n]=d;cout<<i<<'\n'){for(;--i;)cin>>s[i];for(sort(s,s+n);m--;t=upper_bound(s,s+n,d),i+=min(*t-d,d-t[-1]))cin>>d;}}

Measured memory_bytes: 0
package main

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

var sc = bufio.NewScanner(os.Stdin)
var rdr = bufio.NewReaderSize(os.Stdin, 1000000)

func init() {
	sc.Split(bufio.ScanWords)
}

func main() {
	s := readLine()

	ans := int64(0)
	cnt := 0
	for i, ch := range s {
		if ch == 'W' {
			ans += int64(i - cnt)
			cnt++
		}
	}

	fmt.Println(ans)
}

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

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

func nextInt() int {
	sc.Scan()
	i, e := strconv.Atoi(sc.Text())
	if e != nil {
		panic(e)
	}
	return i
}

func nextI64() int64 {
	sc.Scan()
	i, e := strconv.ParseInt(sc.Text(), 10, 64)
	if e != nil {
		panic(e)
	}
	return i
}

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

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

func anser(b bool, y string, n string) string {
	if b {
		return y
	}
	return n
}

Measured memory_bytes: 1280
s=list(input())
ans=0
i=0
comp_s=[]
while i<len(s):
    if s[i]=='<':
        comp_s.append('<')
        tmp=0
        while i<len(s) and s[i]=='<':
            i+=1
            tmp+=1
        comp_s.append(tmp)
    elif s[i]=='>':
        comp_s.append('>')
        tmp=0
        while i<len(s) and s[i]=='>':
            i+=1
            tmp+=1
        comp_s.append(tmp)
#print(comp_s)
    
j=1
sdata=[]
if comp_s[0]=='>':
    sdata.append((0,comp_s[1]))
    j+=2
for i in range(j,len(comp_s)-2,4):
    sdata.append((comp_s[i],comp_s[i+2]))
if comp_s[-2]=='<':
    sdata.append((comp_s[-1],0))
#print(sdata)

for l,r in sdata:
    ans+=l*(l-1)//2+r*(r-1)//2+max(l,r)
print(ans)
    
    

Measured memory_bytes: 26092
use std::collections::BTreeMap;
use std::io::prelude::*;
use std::io::stdin;
use std::str::FromStr;

fn main() {
    let n: usize = read();
    let a: Vec<u64> = (0..n).map(|_| read()).collect();

    let mut map = BTreeMap::new();

    for &a_i in a.iter() {
        *map.entry(a_i).or_insert(0) += 1;
    }

    let ans = if a.iter().all(|&x| x == 0)
        || (n % 3 == 0 && map.len() == 2 && map.get(&0) == Some(&(n / 3)))
        || (n % 3 == 0
            && map.len() == 3
            && map.keys().fold(0, |a, x| a ^ x) == 0
            && map.values().all(|x| *x == n / 3))
    {
        "Yes"
    } else {
        "No"
    };

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

#[allow(dead_code)]
fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let token: String = stdin
        .lock()
        .bytes()
        .map(|b| b.unwrap() as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().unwrap()
}


Measured memory_bytes: 6396
#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define rrep(ri,n) for(int ri = (int)(n-1); ri >= 0; ri--)
#define rep2(i,x,n) for(int i = (int)(x); i < (int)(n); i++)
#define rrep2(ri,x,n) for(int ri = (int)(n-1); ri >= (int)(x); ri--)
#define repit(itr,x) for(auto itr = x.begin(); itr != x.end(); itr++)
#define rrepit(ritr,x) for(auto ritr = x.rbegin(); ritr != x.rend(); ritr++)
#define ALL(x) x.begin(), x.end()
using ll = long long;
using namespace std;

int main(){
  int n, q;
  cin >> n >> q;
  vector<int> a(n);
  rep(i, n) cin >> a.at(i);
  vector<pair<int, ll>> ans;
  ll sl = 0, sr = 0;
  rep(i, n){
    if(i < n/2) sl += a.at(i);
    else sr += a.at(i);
  }
  ll sum = sl + sr;
  
  int li = 0, ri = n/2;
  ans.push_back({1, sr});
  if(n % 2 == 0){
    li++;
  }
  while(ri < n){
    int l = a.at(li), r = a.at(ri);//[l,r)
    int m = (l+r)/2;
    m++;
    ll nx = ans.back().second - r + l;
    ans.push_back({m, nx});
    li += 2; ri += 1;
  }
  // for(auto p : ans){
  //   cerr << p.first << " " << p.second << endl;
  // }
  // cerr << "----------------" << endl;
  rep(_q, q){
    int x;
    cin >> x;
    auto itr = lower_bound(ALL(ans), make_pair(x, 0LL));
    auto mitr = itr;
    if(mitr != ans.begin()) mitr--;
    if(itr != ans.end() && itr->first == x) mitr = itr;
    cout << mitr->second << endl;
  }
  return 0;
}

Measured memory_bytes: 4644
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<map>
#include<math.h>
#include<queue>
#include<deque>
#include<stack>
#include<cstdio>
#include<utility>
#include<set>
#include<list>
#include<cmath>
#include<stdio.h>
#include<string.h>
#include<iomanip>
using namespace std;
#define FOR(i, a, b) for (ll i = (a); i <= (b); i++)
#define REP(i, n) FOR(i, 0, n - 1)
#define NREP(i, n) FOR(i, 1, n)
using ll = long long;
using pii = pair<int, int>;
using piii = pair<pii, pii>;
const int dx[4] = { 0, -1, 1, 0 };
const int dy[4] = { -1, 0, 0, 1 };
const int INF = 1e9 + 7;
int gcd(int x, int y) {
	if (x < y)swap(x, y);
	if (y == 0)return x;
	return gcd(y, x%y);
}

template<class T1, class T2> void chmin(T1 &a, T2 b) { if (a>b)a = b; }

template<class T1, class T2> void chmax(T1 &a, T2 b) { if (a<b)a = b; }
template<class T>
void Add(T &a, const T &b, const T &mod = 1000000007) {
	int val = ((a % mod) + (b % mod)) % mod;
	if (val < 0) { val += mod; }
	a = val;
}
////////////////////////////////////////

int main() {
	ll N, M;
	cin >> N >> M;
	if (N == 1 && M == 1) {
		cout << 1 << endl;
		return 0;
	}
	if (N == 1 || M == 1) {
		cout << N + M - 3 << endl;
	}
	else {
		cout << (N - 2)*(M - 2) << endl;
	}
    return 0;
}

Measured memory_bytes: 256
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<cctype>
#include<complex>
#include<iostream>
#include<sstream>
#include<algorithm>
#include<functional>
#include<vector>
#include<string>
#include<stack>
#include<queue>
#include<map>
#include<set>
#include<bitset>
using namespace std;
const int dx[] = {1,0,-1,0},dy[] = {0,1,0,-1};
#define INF 1e+8
#define EPS 1e-8
#define rep(i,j) for(int i = 0; i < (j); i++)
#define reps(i,j,k) for(int i = j; i < k; i++)
typedef long long ll;
typedef pair<int,int> Pii;
int main(){
	int n;
	cin >> n;
	string change[] = {"",".,!? ","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};	
	while(n--){
		string str;
		cin >> str;
		int len = str.size();
		string ans = "";
		rep(i,len){
			if(str[i] == '0')continue;
			int sub = i;
			while(str[i] == str[++sub]);
			ans += change[str[sub-1]-48][(sub-i-1)%change[str[sub-1]-48].size()];
			i = sub;
		}
		
		cout << ans << endl;
	}
	
	return 0;
}

Measured memory_bytes: 1216
n = int(input())
a = list(map(int, input().split()))

s = 1000
j = 0

for i in range(n-1):
    if a[i] < a[i+1]:
        j += s // a[i]
        s = s % a[i]
    elif a[i] > a[i+1]:
        s += j * a[i]
        j = 0

s += j * a[n-1]
j = 0

print(s)

Measured memory_bytes: 62000
from collections import Counter

s = input()
t = input()

count_s = Counter()
count_t = Counter()

for i in s:
    count_t[i] += 1

for j in t:
    count_s[j] += 1


s_list = sorted(list(dict(count_s).values()))
t_list = sorted(list(dict(count_t).values()))

if s_list == t_list:
    print('Yes')
else:
    print('No')


Measured memory_bytes: 3888
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
const int oo = 1000000000;
int n, k, v[N], dp[N];
int f(int pos) {
	if(dp[pos] != -1)
		return dp[pos];
	if (pos == (n - 1))
		return 0;
	if (pos > n)
		return oo;
	int answer = oo;
	for(int i = 1; i <= k; i++)
		answer = min(answer, f(pos + i) + abs(v[pos] - v[pos + i]));
	return dp[pos] = answer;
}
int main(){
	cin >> n >> k;
	memset(dp, -1, sizeof dp);
	for(int i = 0; i < n; i++)
		cin >> v[i];
	cout << f(0) << "\n";
    return 0;
}


Measured memory_bytes: 12152
import Control.Monad
import Control.Applicative
import Data.List

main = do
  xs <- input read :: IO [Int]
  mapM_ putStrLn $ solve xs

solve :: [Int] -> [String]
solve xs = map f xs
  where f z = intercalate " " . filter (not . null) $ zipWith (\x y -> if x == 1 then y else "") (i2b z) tbl

i2b :: Int -> [Int]
i2b 0 = []
i2b x = x `mod` 2 : i2b (x `div` 2)

tbl :: [String]
tbl = ["1", "2", "4", "8", "16", "32", "64", "128", "256", "512"]


input :: (String -> a) -> IO [a]
input f = map f . lines <$> getContents 

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

namespace A
{
    class Program
    {
        public static void Main(string[] args)
        {
            string[,] c = new string[3, 3];

            for (int i = 0; i < 3; i++) {
                string s = Console.ReadLine();

                for (int q = 0; q < 3; q++) {
                    c[i, q] = s.ToCharArray()[q].ToString();
                }
            }

            Console.WriteLine(c[0, 0]+c[1, 1]+c[2, 2]);

            Console.ReadLine();
        }
    }
}

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

int main()
{

    int a,b,c,p,q,r,A,B;

    cin>>a;

    p=a/100;
    q=a%100;



if ((q>0&&q<13)&&(p>0&&p<13))
        cout<<"AMBIGUOUS"<<endl;

       else if (p>0&&p<13)
        cout<<"MMYY"<<endl;


   else if(q>0&&q<13)
        cout<<"YYMM"<<endl;


    else
        cout<<"NA"<<endl;

    return 0;
}





Measured memory_bytes: 256
#include <iostream>
#include<vector>
#include <set>
#include <map>
#include <cmath>
#include <algorithm>
typedef long long int lld;
typedef unsigned long long int llu;
using namespace std;
const int m=1e9;
int main()
{
	int n,w,i;
	cin>>n>>w;
	int wt[n],v[n];
	for(i=0;i<n;i++) cin>>wt[i]>>v[i];
	lld k[n+1][w+1],j;
	for(i=0;i<=n;i++)
	{
		for(j=0;j<=w;j++)
		{
			if(i==0||j==0) k[i][j]=0;
			else if(wt[i-1]<=j)
			{
				k[i][j]=max(k[i-1][j],v[i-1]+k[i-1][j-wt[i-1]]);
			}
			else k[i][j]=k[i-1][j];
		}
	}
	cout<<k[n][w];
}

Measured memory_bytes: 79104
def main():
    n, m = map(int, input().split())
    s = []

    for _ in range(m):
        r = [int(x) for x in input().split()]
        s.append(r[1:])
    
    p = [int(s) for s in input().split()]

    print(solve(m, n, s, p))

def solve(m, n, s, p):
    c = 0
    for bits in range(2 ** n):
        for i in range(m):
            if not check(bits, s[i], p[i]):
                break
        else:
            c += 1
    return c

def check(bits, si, pi):
    n = 0
    for sij in si:
        if bits & (1 << (sij - 1)):
            n += 1
    
    if n % 2 == pi:
        return True

    return False


main()


Measured memory_bytes: 3064
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<list>
#include<set>
#include<map>
#include<utility>
#include<cmath>
#include <iomanip>
#include<stack>


#define rep(i,x) for(int i=0;i<(int)(x);i++)
#define reps(i,x) for(int i=1;i<=(int)(x);i++)
#define rrep(i,x) for(int i=((int)(x)-1);i>=0;i--)
#define rreps(i,x) for(int i=((int)(x));i>0;i--)

#define all(x) (x).begin(),(x).end()
#define SZ(x) ((int)(x).size())
#define INF 2e9

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
typedef long long ll;
typedef long double ld;
typedef std::pair<ll, ll> P;
int gcd(int a,int b){return b?gcd(b,a%b):a;}


using namespace std;

bool pairCompare(const P& firstElof, const P& secondElof)
{
    return firstElof.second < secondElof.second;
}
 

int main()
{
    ll n;
    cin >> n;

    vector<P> vp(n);

    rep(i, n){
        cin >> vp[i].first >> vp[i].second;
    }

    sort(all(vp), pairCompare);

    ll cnt = 0;

    rep(i, n){
        cnt += vp[i].first;
        if(cnt > vp[i].second){
            cout << "No";
            return 0;
        }
    }

    cout << "Yes";
    return 0;
}

Measured memory_bytes: 3328
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main() {
  ll n,k ;
  cin >> n >> k ;
  vector<ll> A(n);
  for(ll i=0;i<n;i++){
    cin >> A.at(i) ;
  }
  ll ans = 1e16;
  for(ll i=0;i<n-k+1;i++){
    ans = min(ans,min(abs(A.at(i)),abs(A.at(k-1+i)))+abs(A.at(i)-A.at(k-1+i)));
  }
  cout << ans << endl;
}





Measured memory_bytes: 1024
#include <bits/stdc++.h>
#include <cstring>
#include <limits>
using namespace std;
#define ll long long int
#define lli long long int
#define fw(i, s, e) for (ll i = s; i < e; ++i)
#define fe(i, s, e) for (ll i = s; i <= e; ++i)
#define fb(i, e, s) for (ll i = e; i >= s; --i)
#define L(T)  \
    ll T;     \
    cin >> T; \
    while (T--)
#define FASTIO                   \
    ios::sync_with_stdio(false); \
    cin.tie(nullptr);            \
    cout.tie(nullptr);
#define mem(a, i) memset(a, i, sizeof(a))
#define ld long double
#define endl "\n"
#define in(P) \
    ll P;     \
    cin >> P;
int main()
{
    FASTIO
    // L(T)
    {
        // char s[45];
        string s;
        cin >> s;
        if (s == "AAA")
        {
            cout << "No" << endl;
        }
        else if (s == "BBB")
            cout << "No" << endl;
        else
        {
            cout << "Yes" << endl;
        }
    }
    return 0;
}

Measured memory_bytes: 3660
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef vector<string> vs;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<vector<int>> vvi;
typedef vector<vector<string>> vvs;
typedef vector<vector<char>> vvc;
typedef vector<vector<bool>> vvb;
typedef pair<int,int> P;
#define vrep(v,n) for(int i=0;i<n;i++){cin >> v.at(i);} //配列vにn個の要素を入力する
#define rep(i, l, n) for (int i = l; i < (int)(n); i++)
#define repn(i, l, n) for (int i = l; i <= (int)(n); i++)
#define push_back pb

const int mod = 1000000007;
const int inf = 1e9;

int main(){
    string s;
    cin >> s;
    if(s[2]==s[3]&&s[4]==s[5]){cout << "Yes";}else{cout << "No";}
}

Measured memory_bytes: 256
#include <iostream>
#include <stdio.h>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <algorithm>
#include <vector>
#include <string>
#include <stdlib.h>
#include <queue>
#include <stack>
#include <utility>
#include <fstream>
#include <random>
#include <map>
#include <unordered_map>
#include <cstdlib>
#include <functional>
#include <random>
#include <time.h>
#include <chrono>
#include <sstream>
#include <iomanip>
#define rep(i,n) for(int i=0;i<n;i++)
#define rrep(i,n) for(int i=n-1;i>=0;i--)
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define ll long long
#define INF 1000000001
#define mod 1000000007
#define SORT(s) sort(s.begin(), s.end());
#define reverse(s) reverse(s.begin(), s.end());
#define P pair<int,int>
#define mp make_pair
#define valid(x,y,h,w) (0<=x&&x<h&&0<=y&&y<w)
int dx[4] = { 0,1,0,-1 };
int dy[4] = { 1,0,-1,0 };
using namespace std;
int POW(int x, int y) { return int(pow(double(x), double(y))); }
double log(double a, double b) { return log(b) / log(a); }




int main() {
	string s;
	cin >> s;
	int n = s.size();
	if (n == 1) {
		cout << 3 << endl;
		return 0;
	}
	
	vector<ll> dp1(n),dp2(n);
	dp1[0] = 2;
	dp2[0] = 1;

	FOR(i, 1, n) {
		if (s[i] == '1') {
			dp1[i] = dp1[i - 1] * 2;
			dp2[i] = dp1[i - 1] + dp2[i - 1] * 3;
		}
		else {
			dp1[i] = dp1[i - 1];
			dp2[i] = dp2[i - 1] * 3;
		}
		dp1[i] = dp1[i] % mod;
		dp2[i] = dp2[i] % mod;
	}
	cout << (dp1[n - 1] + dp2[n - 1]) % mod << endl;
}



Measured memory_bytes: 2048
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <queue>
#include <cmath>
#include <climits>
#include <iomanip>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
int main(){
  string s;
  cin >> s;
  ll res = 0;
  if(s[0] == '1')res++;
  if(s[1] == '1')res++;
  if(s[2] == '1')res++;
  cout << res << endl;
}

Measured memory_bytes: 3628
import java.io.*;
import java.util.*;

public class Main {
	long solve(int[] a) {
		int n = a.length / 2;
		long ans = 0, ansRight = 0;
		for (int i = 0; i < n; i++) {
			ans += a[2 * i];
			ansRight += a[2 * i + 1];
		}
		ans = Math.min(ans, ansRight);
		int[] c = Arrays.copyOf(a, a.length);
		Arrays.sort(c);
		long sum = 0;
		for (int i = 0; i < n - 2; i++) {
			sum += c[i];
		}
		for (int i = 0; i < n; i++) {
			int x = Math.min(a[2 * i], a[2 * i + 1]);
			int y = Math.max(a[2 * i], a[2 * i + 1]);
			ans = Math.min(ans, sum + Math.max(x, c[n - 2]) + Math.max(y, c[n - 1]));
		}
		return ans;
	}
	
	void run() {
//		stress();
		int n = in.nextInt();
		int[] a = new int[2 * n];
		for (int i = 0; i < n; i++) {
			a[2 * i] = in.nextInt();
			a[2 * i + 1] = in.nextInt();
		}
		out.println(solve(a));
	}

	void stress() {
		Random r = new Random(566);
		for (;;) {
			int[] a = new int[2 * (2 + r.nextInt(5))];
			for (int i = 0; i < a.length; i++) {
				a[i] = r.nextInt(a.length);
			}
			System.out.println(Arrays.toString(a));
			long solve = solve(a);
			long solveSlow = solveSlow(a);
			if (solve != solveSlow) {
				System.out.println("! " + solve + " " + solveSlow);
				solve(a);
				return;
			}
		}
	}
	
	long solveSlow(int[] a) {
		int n = a.length / 2;
		boolean[] mark = new boolean[n];
		return search(a, mark, 0, 0);
	}
	
	long search(int[] a, boolean[] mark, int x, long sum) {
		mark[x] = true;
		int n = a.length / 2;
		boolean last = true;
		long r = Long.MAX_VALUE;
		for (int y = 0; y < n; y++) {
			if (mark[y]) {
				continue;
			}
			last = false;
			r = Math.min(search(a, mark, y, sum + Math.min(a[2 * x], a[2 * y + 1])), r);
		}
		mark[x] = false;
		return last ? sum + Math.min(a[2 * x], a[1]) : r;
	}

	static MyScanner in;
	static PrintWriter out;

	public static void main(String[] args) throws IOException {
		boolean stdStreams = true;
		String fileName = Main.class.getSimpleName().replaceFirst("_.*", "").toLowerCase();
		String inputFileName = fileName + ".in";
		String outputFileName = fileName + ".out";
		
		Locale.setDefault(Locale.US);
		BufferedReader br;
		if (stdStreams) {
			br = new BufferedReader(new InputStreamReader(System.in));
			out = new PrintWriter(System.out);
		} else {
			br = new BufferedReader(new FileReader(inputFileName));
			out = new PrintWriter(outputFileName);
		}
		in = new MyScanner(br);
		int tests = 1;//in.nextInt();
		for (int test = 0; test < tests; test++) {
			new Main().run();
		}
		br.close();
		out.close();
	}
	
	static class MyScanner {
		BufferedReader br;
		StringTokenizer st;

		MyScanner(BufferedReader br) {
			this.br = br;
		}
		
		void findToken() {
			while (st == null || !st.hasMoreTokens()) {
				try {
					st = new StringTokenizer(br.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
		}
		
		String next() {
			findToken();
			return st.nextToken();
		}
		
		int nextInt() {
			return Integer.parseInt(next());
		}
		
		long nextLong() {
			return Long.parseLong(next());
		}
		
		double nextDouble() {
			return Double.parseDouble(next());
		}
	}
}


Measured memory_bytes: 45136
import itertools
n  = int(input())
s = []
for i in range(n):
    s.append(int(input()))

s.sort()

sum = 0
for i in range(n):
    sum += s[i]


if sum%10!=0:
    print(sum)
else:
    preSum = sum
    for i in range(n):
        if s[i]%10!=0:
            sum = sum-s[i]
            break
    
    if sum!=preSum:
        print(sum)
    else:
        print(0)

Measured memory_bytes: 3064
from collections import deque
n, q = map(int, input().split())

ki = [[] for i in range(n)]
for i in range(n-1):
  a,b = map(int, input().split())
  a -= 1
  b -= 1
  ki[a].append(b)
  ki[b].append(a)

cnt = [0 for i in range(n)]
for i in range(q):
  p, x = map(int, input().split())
  p -= 1
  cnt[p] += x

visited = [False for i in range(n)]
visited[0] = True

queue = deque()
queue.append(0)
while queue:
  x = queue.popleft()
  for i in ki[x]:
    if visited[i] == True:
      continue
    cnt[i] += cnt[x]
    queue.append(i)
    visited[i] = True
print (*cnt)

Measured memory_bytes: 105704
package main

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

func main() {
	N := ReadInt()
	A := make([]int, N)
	B := make([]int, N)
	for i := 0; i < N; i++ {
		A[i], B[i] = ReadInt(), ReadInt()
	}
	ans := 0
	for i := N - 1; i >= 0; i-- {
		A[i] += ans
		if r := A[i] % B[i]; r > 0 {
			ans += B[i] - r
		}
	}
	fmt.Println(ans)
}

var reader = bufio.NewReader(os.Stdin)

func Scan(a ...interface{}) {
	if _, err := fmt.Fscan(reader, a...); err != nil {
		panic(err)
	}
}
func ReadInt() (i int)       { Scan(&i); return }
func ReadString() (s string) { Scan(&s); return }
func ReadInts(n int) []int {
	v := make([]int, n)
	for i := 0; i < n; i++ {
		Scan(&v[i])
	}
	return v
}


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

int main(){
        int n,i,p,m=1e6,cnt=0;
        cin >> n;
        for(i=0;i<n;++i){
                cin >> p;
                if(p<=m) ++cnt;
                m = min(m,p);
        }
        cout << cnt << endl;
        return 0;
}

Measured memory_bytes: 3640
#include<bits/stdc++.h>
#define REP(i,n) for(int i=0,i##_len=(n);i<i##_len;++i)
#define int long long
using namespace std;
typedef pair<int,int> P;
constexpr int mod=1e9+7;
int N,K;
int a[100];
int dp[101][100001]={};

signed main(){
    cin>>N>>K;
    REP(i,N) cin>>a[i];
    dp[N][K]=1;
    for(int i=N-1;i>=0;--i) for(int j=K;j>=0;--j){
        if(j==K) dp[i][j]=dp[i+1][j];
        else if(j+a[i]+1>K) dp[i][j] = dp[i+1][j] + dp[i][j+1];
        else dp[i][j]=dp[i+1][j]+dp[i][j+1]-dp[i+1][j+a[i]+1];
        dp[i][j]=(dp[i][j]+mod)%mod;
        //cout<<i<<" "<<j<<" "<<dp[i][j]<<endl;
    }
    cout<<dp[0][0]<<endl;
}


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

int n, cnt = 0;
long long ans = 0;
string s;

signed main() {
	cin >> s;
	for(int i = 0; i < (int)s.size() - 1; i++) if(s[i] == 'A') cnt++; else if(s[i] == 'B' && s[i + 1] == 'C') ans += cnt, s[i + 1] = 'A', cnt--; else if(s[i] != 'A') cnt = 0;
	cout << ans;
}

Measured memory_bytes: 640
#include <stdio.h>
int main(void)
{
	char n[5];
	scanf("%s",n);
	char c = 'a';
	int k=0;
	for(int i=0;i<4;i++)
	{
		if((int)n[i] == (int)c)
		{
			k++;
			break;
		}
		c = n[i];
	}
	if(k==1)
		printf("Bad\n");
	else
		printf("Good\n");
	return 0;
}


Measured memory_bytes: 128
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for (int (i)=0;(i)<(n);i++)
#define INF 1001001001
#define LLINF 1001001001001001001
#define MOD 1000000007
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
#define ALL(v) v.begin(), v.end()
typedef long long ll;

int main(){
    ll n,a,b;
    cin >> n >> a >> b;

    ll tem = n/(a+b);
    ll x = n%(a+b);

    if(x <= a)cout << a*tem + x << endl;
    else cout << a*tem + a << endl;

    return 0;
}





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

#define int long long
#define double long double
#define ff first
#define ss second
#define endl '\n'
#define ii pair<int, int>
#define mp make_pair
#define mt make_tuple
#define DESYNC                      \
  ios_base::sync_with_stdio(false); \
  cin.tie(0);                       \
  cout.tie(0)
#define pb push_back
#define vi vector<int>
#define vii vector<ii>
#define all(x) x.begin(), x.end()
#define EPS 1e-9
#define INF 1e18
#define ROOT 1
#define M 1000000007
#define curtime chrono::steady_clock::now().time_since_epoch().count
#define rep(i, beg, n, s) for (int i = beg; i < n; i += s)
const double PI = acos(-1);

using namespace std;

inline int mod(int n, int m = M) {
  int ret = n % m;
  if (ret < 0) ret += m;
  return ret;
}

int exp(int n, int k) {
  if (k == 0) return 1;
  if (k == 1) return n;
  int ax = exp(n, k / 2);
  ax = mod(ax * ax);
  if (k % 2) ax = mod(ax * n);
  return ax;
}

int gcd(int a, int b) {
  if (a == 0)
    return b;
  else
    return gcd(b % a, a);
}

int get_cuts(int cur, int mx) { return (cur - 1) / mx; }

//#define MULTIPLE_TEST_CASE
void solution() {
  int n, k;
  cin >> n >> k;
  int v[n];
  for (int i = 0; i < n; i++) cin >> v[i];
  int l = 1, r = 1123456789;
  int ans = -1;
  while (l <= r) {
    int m = (l + r) >> 1;
    // cout << "testing " << m << endl;
    // check whether m is possible
    int cuts = 0;
    for (int i = 0; i < n; i++) {
      // cout << get_cuts(v[i], m) << " ";
      cuts += get_cuts(v[i], m);
    }
    // cout << endl;
    if (cuts <= k) {
      ans = m;
      r = m - 1;
    } else {
      l = m + 1;
    }
  }
  cout << ans << endl;
}

int32_t main() {
  DESYNC;
  mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
  int t = 1;
#ifdef MULTIPLE_TEST_CASE
  cin >> t;
#endif
  while (t--) solution();
}


Measured memory_bytes: 5112
#include <iostream>
#include <string>
#include <vector>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <cstdio>
#include <functional>
#include <set>
#include <sstream>
#include <map>
 
using namespace std;
 
const double eps=1e-10;
 
int main()
{
	int x,y,s,c[14][14]={0};
	char dummy;
	while(cin>>x>>dummy>>y>>dummy>>s){
		x+=2; y+=2;

		c[y][x]++;
		c[y+1][x]++; c[y-1][x]++;
		c[y][x+1]++; c[y][x-1]++;

		if(s>=2){
			c[y-1][x-1]++; c[y-1][x+1]++;
			c[y+1][x-1]++; c[y+1][x+1]++;
		}

		if(s==3){
			c[y-2][x]++; c[y+2][x]++;
			c[y][x-2]++; c[y][x+2]++;
		}

	}

	int w=0,d=0;
	for(int i=2;i<12;i++){
		for(int j=2;j<12;j++){
			if(c[i][j]==0) w++;
			d=max(d,c[i][j]);
		}
	}

	cout<<w<<endl<<d<<endl;


	return 0;
}

Measured memory_bytes: 1160
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.util.StringTokenizer;

public class Main {

	public static void main(String[] args) throws IOException {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskX solver = new TaskX();
		solver.solve(1, in, out);
		out.close();
	}

	static int INF = 1 << 30;
	static long LINF = 1L << 55;
	static int MOD = 1000000007;
	static int[] mh4 = { 0, -1, 1, 0 };
	static int[] mw4 = { -1, 0, 0, 1 };
	static int[] mh8 = { -1, -1, -1, 0, 0, 1, 1, 1 };
	static int[] mw8 = { -1, 0, 1, -1, 1, -1, 0, 1 };

	static class TaskX {

		public void solve(int testNumber, InputReader in, PrintWriter out) {

			char[] s = in.nextString().toCharArray();
			long k = in.nextLong();
			int idx = -1;

			char t = '1';
			for (int i = 0; i < s.length; i++) {
				if (s[i] != '1') {
					t = s[i];
					idx = i+1;
					break;
				}
			}

			if (k <= 100 && k < idx) {
				out.println(s[(int)(k-1)]);
				return;
			}

			if (t != '1') {
				out.println(t);
			} else {
				out.println('1');
			}
		}
	}

	static class InputReader {
		BufferedReader in;
		StringTokenizer tok;

		public String nextString() {
			while (!tok.hasMoreTokens()) {
				try {
					tok = new StringTokenizer(in.readLine(), " ");
				} catch (IOException e) {
					throw new InputMismatchException();
				}
			}
			return tok.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(nextString());
		}

		public long nextLong() {
			return Long.parseLong(nextString());
		}

		public double nextDouble() {
			return Double.parseDouble(nextString());
		}

		public int[] nextIntArray(int n) {
			int[] res = new int[n];
			for (int i = 0; i < n; i++) {
				res[i] = nextInt();
			}
			return res;
		}

		public int[] nextIntArrayDec(int n) {
			int[] res = new int[n];
			for (int i = 0; i < n; i++) {
				res[i] = nextInt() - 1;
			}
			return res;
		}

		public long[] nextLongArray(int n) {
			long[] res = new long[n];
			for (int i = 0; i < n; i++) {
				res[i] = nextLong();
			}
			return res;
		}

		public long[] nextLongArrayDec(int n) {
			long[] res = new long[n];
			for (int i = 0; i < n; i++) {
				res[i] = nextLong() - 1;
			}
			return res;
		}

		public InputReader(InputStream inputStream) {
			in = new BufferedReader(new InputStreamReader(inputStream));
			tok = new StringTokenizer("");
		}
	}

}


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

#define INF (INT32_MAX)
#define MOD (1000000000+7)
#define MAX 100

int N, L;
string S[MAX];

int main() {
	cin >> N >> L;
	for( int i = 0; i < N; i++ ) {
		cin >> S[i];
	}

	for( int i = 0; i < N - 1; i++ ) {
		for( int j = i + 1; j < N; j++ ) {
			if( S[j] < S[i] ) {
				string tmp = S[j];
				S[j] = S[i];
				S[i] = tmp;
			}
		}
	}

	for( int i = 0; i < N; i++ ) {
		cout << S[i];
	}
	cout << endl;

	return 0;
}


Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <queue>
#include <unordered_map>
#include <map>
#include <string>
#include <iomanip>
#include <cmath>
#include <cstring>
#include <algorithm> 
#include <ctime>

#define MaxT 600000
#define MaxN 200005
#define INF 2140000000

using namespace std;

long long T[MaxT],P,Val;
long long N,K,ans=0;
struct spec
{
	long long val;
	int pos;
}S[MaxN];
bool cond( spec a,spec b)
{
	return a.val<b.val||(a.val==b.val&&a.pos<b.pos);
}
void Update(int node,int start,int end)
{
	if(start==end)
		T[node]++;
	else
	{
		int mid=(start+end)>>1;
		if(P<=mid)
			Update(2*node,start,mid);
		else Update(2*node+1,mid+1,end);
		T[node]=T[2*node]+T[2*node+1];
	}
}
void Query(int node,int start,int end)
{
	if(end<=P)
		Val+=T[node];
	else
	{
		int mid=(start+end)>>1;
		Query(2*node,start,mid);
		if(mid<P)
			Query(2*node+1,mid+1,end);
	}
}
int main()
{
	cin>>N>>K;
	for(int i=1;i<=N;i++)
		cin>>S[i].val,S[i].val+=S[i-1].val-K,S[i].pos=i;
	sort(S,S+1+N,cond);
	for(int i=0;i<=N;i++)
	{
		P=S[i].pos;
		Update(1,0,N);
		if(P==0)
			continue;
		P--;
		Val=0;
		Query(1,0,N);
		ans=ans+1LL*Val;
	}
	cout<<ans;
	return 0;
}

Measured memory_bytes: 7424
// C - Walk on Multiplication Table
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rp(i,s,e) for(int i=(s);i<(e);++i)

int main(){
	ll N; cin>>N;
	ll ans = LLONG_MAX;
	ll n = sqrt(N);
	rp(a, 1, n+1){
		if(N%a) continue;
		ll b = N/a;
		ans = min(ans, a + b - 2);
	}
	cout<< ans <<endl;
}

Measured memory_bytes: 256
#include <cstdio>
#include <cmath>
#define printjudge(cond) {if(cond) printf("Yes\n"); else printf("No\n");}

int main(){
    int N, A, min, max;
    min = 1000000000+1;
    max = 0;
    scanf("%d", &N);
    for(int i=0; i<N; i++){
        scanf("%d", &A);
        if(A>max) max = A;
        if(A<min) min = A;
    }
    printf("%d\n", max - min);
    return 0;
}


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

using namespace std;

int main()
{
	int k;
	int data[] = { 1, 1, 1, 2, 1, 2, 1, 5, 2, 2, 1, 5, 1, 2, 1, 14, 1, 5, 1, 5, 2, 2, 1, 15, 2, 2, 5, 4, 1, 4, 1, 51 };
	cin >> k;

	cout << data[k - 1];
    
	return 0;
}

Measured memory_bytes: 256
#include <stdio.h>
int main()
{
    int N;
    scanf("%d", &N);
    int a;
    for (int i = 0; i < N; i++)
    {
        scanf("%d", &a);
        if (a % 2 == 0)
        {
            if (!(a % 3 == 0 | a % 5 == 0))
            {
                printf("DENIED");
                return 0;
            }
        }
    }
    printf("APPROVED");
    return 0;
}

Measured memory_bytes: 128
using System;
using System.Collections.Generic;
class Program
{
	static void Main(string[] args)
	{
		string[] str = Console.ReadLine().Split(' ');
		int W = int.Parse(str[0]);
		int H = int.Parse(str[1]);
		int x = int.Parse(str[2]);
		int y = int.Parse(str[3]);
		int r = int.Parse(str[4]);
		string s = "";
		if(x-r >= 0 && y-r >= 0 && x+r <= W && y+r <= H){
			s = "Yes";
		} else {
			s = "No";
		}
		Console.WriteLine(s);
	}
}


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

struct SuffixArray{
	string s;
	vector<int> sa;

	int operator[](int i) const{ return sa[i]; }

	SuffixArray(const string &t) : s(t),sa(s.size() + 1){
		s += '$';
		int n = s.size();
		iota(sa.begin(),sa.end(),0);
		sort(sa.begin(),sa.end(),[&](int a,int b){ return s[a] < s[b]; });
		vector<int> rnk(s.begin(),s.end()),cnt(n),nxt(n);
		for(int k = 1;k < n;k <<= 1){
			nxt[sa[0]] = 0;
			for(int i = 1;i < n;i++){
				nxt[sa[i]] = (rnk[sa[i - 1]] == rnk[sa[i]]
				&& rnk[(sa[i - 1] + k / 2) % n] == rnk[(sa[i] + k / 2) % n])
				? nxt[sa[i - 1]] : i;
			}
			rnk.swap(nxt);

			iota(cnt.begin(),cnt.end(),0);
			for(int i = 0;i < n;i++){
				int s1 = (sa[i] - k + n) % n;
				nxt[cnt[rnk[s1]]++] = s1;
			}
			sa.swap(nxt);
		}
	}

	inline int lower_bound(const string &t) const{
		return partition_point(sa.begin(),sa.end(),[&](int x){
			return s.compare(x,t.length(),t) < 0;
		}) - sa.begin();
	}

	int upper_bound(string &t) const{
		t.back()++;
		int ret = lower_bound(t);
		t.back()--;
		return ret;
	}

	inline int count(string &t) const{
		return upper_bound(t) - lower_bound(t);
	}
};

signed main(){
	ios::sync_with_stdio(false);
	cin.tie(0);
	string t;
	int q;
	cin >> t >> q;
	SuffixArray sa(t);
	for(int i = 0;i < q;i++){
		string p;
		cin >> p;
		cout << !!sa.count(p) << endl;
	}
}


Measured memory_bytes: 20468
import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n=sc.nextInt();
        int m=sc.nextInt();
        int res=0;
        res=n*(n-1)/2+m*(m-1)/2;
        System.out.println(res);
    }
}

Measured memory_bytes: 21844
#include <bits/stdc++.h>
using namespace std;
 
typedef pair<int, int> ii;
typedef vector<ii> vii;
typedef vector<int> vi;
typedef pair<int,ii> iii;
typedef pair<int, iii> iiii;
typedef pair<double, ii> dii;
typedef long long ll;
typedef pair<ll, ii> lii;
const int INF = 1000000000;
const double EPS = 1e-9;
#define LSOne(S) (S & (-S))
int mods(int a, int b) { return (b + (a%b)) % b; }

int n, m, a, b, dp[100005], indegree[100005];
vi ts;
vector<vi> adjList;
bitset<100005> visited;

void topoSort(int u) {
    visited[u] = 1;
    for (int i = 0; i < adjList[u].size(); i++) {
        int v = adjList[u][i];
        if (!visited[v]) topoSort(v);
    }

    ts.push_back(u);
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
 
    // freopen("input.txt", "r", stdin);
    // freopen("output.txt", "w", stdout);

    cin >> n >> m;
    adjList.resize(n);

    for (int i = 0; i < m; i++) {
        cin >> a >> b;
        adjList[a-1].push_back(b-1);
        indegree[b-1]++;
    }

    for (int i = 0; i < n; i++)
        if (!indegree[i] && !visited[i]) topoSort(i);
    reverse(ts.begin(), ts.end());

    for (int i = 0; i < ts.size(); i++) {
        int u = ts[i];
        for (int j = 0; j < adjList[u].size(); j++) {
            int v = adjList[u][j];
            dp[v] = max(dp[v], dp[u]+1);
        }
    }

    int ans = 0;
    for (int i = 0; i < n; i++)
        ans = max(ans, dp[i]);

    cout << ans << '\n';

    return 0;
}

Measured memory_bytes: 11768
#include<bits/stdc++.h>
#define ll long long
#define mk make_pair
#define pb push_back
#define pa pair<int,int>
#define rint register int
#define debug(x) cerr<<#x<<"="<<x<<"\n"
#define fir first
#define sec second
#define SZ(x) (x).size()
using namespace std;
inline int read(){int w=1,s=0;char ch=getchar();while(!isdigit(ch)){if(ch=='-') w=-1;ch=getchar();} while(isdigit(ch)){s=s*10+ch-'0';ch=getchar();} return w*s;}
struct node{int to,next;} e[101010];
int n,h[1010100],tot,all=0,f[101000],g[101010],size[101010],dep[101010];
char s[1010100];
inline void add(int from,int to){e[++tot].next=h[from];h[from]=tot;e[tot].to=to;}
inline void DFS(int now,int ffa){
	size[now]=0,f[now]=0,g[now]=0;
	
	for(rint i=h[now];i;i=e[i].next) {
		int to=e[i].to;if(to==ffa) continue;
		dep[to]=dep[now]+1;DFS(to,now);
		g[to]+=size[to];f[to]+=size[to];
		if(g[to]<f[now]||g[now]<f[to]) {
			f[now]=max(f[now],f[to])-min(g[now],g[to]);
		}
		else f[now]=(g[now]+g[to])&1; 
		g[now]+=g[to];size[now]+=size[to];
	}
	if(s[now]=='1') size[now]++,all+=dep[now];
//	debug(now);debug(f[now]);
}
int main()
{	
	n=read();
	scanf("%s",s+1);
	for(rint i=1;i<n;++i) {
		int u=read(),v=read();
		add(u,v);add(v,u);
	}
	int res=2e9;
	for(rint i=1;i<=n;++i) {
		all=0;dep[i]=0;
		DFS(i,0);
		
		if(f[i]==0) res=min(res,all/2);
	}
	if(res>1e9) cout<<"-1\n";
	else cout<<res<<"\n";
	return 0;
}	

Measured memory_bytes: 2432
from collections import Counter

n = int(input())
a = list(map(int,input().split()))
A = list(set(a))
A.sort()
amax = A[-1]
sieve = [1]*(amax+1)
ans = []

for i in A:
  for j in range(2,amax//i + 1):
    sieve[i*j] = 0

for i in A:
  if sieve[i] == 1:
    ans.append(i)

c = Counter(a)
ansl =len(ans)

for k,v in c.items():
  if sieve[k] == 1 and v >= 2:
    ansl -= 1
    
print(ansl)


Measured memory_bytes: 48816
#include <cstdio>
using namespace std;

int main(){
	bool stu[31];
	int n;
	
	for(int i = 0; i <= 30; i++) stu[i] = false;
	
	for(int i = 0; i < 28; i++){
		scanf("%d", &n);
		
		stu[n] = true;
	}
	
	for(int i = 1; i <= 30; i++){
		if(!stu[i]) printf("%d\n", i);
	}
	
	return 0;
}

Measured memory_bytes: 1024
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i,n) for(int (i)=0;(i)<(int)(n);++(i))
#define all(x) (x).begin(),(x).end()
#define pb push_back
#define fi first
#define se second
#define dbg(x) cout<<#x" = "<<((x))<<endl
template<class T,class U> ostream& operator<<(ostream& o, const pair<T,U> &p){o<<"("<<p.fi<<","<<p.se<<")";return o;}
template<class T> ostream& operator<<(ostream& o, const vector<T> &v){o<<"[";for(T t:v){o<<t<<",";}o<<"]";return o;}

const ll mod = 1000000009;

using vl = vector<ll>;
using mat = vector<vl>;

mat mul(const mat &A, const mat &B){
    int n = A.size();
    mat C(n,vl(n));
    rep(i,n)rep(j,n)rep(k,n) (C[i][j] += A[i][k]*B[k][j]) %= mod;
    return C;
}

mat mat_pow(const mat &A, ll x){
    int n = A.size();

    mat ret(n,vl(n));
    rep(i,n) ret[i][i] = 1;

    mat P(A);
    while(x){
        if(x&1) ret = mul(ret,P);
        P = mul(P,P);
        x>>=1;
    }
    return ret;
}

vl mul(const mat &A, const vl &b){
    int n = A.size();
    vl ret(n);
    rep(i,n)rep(j,n) (ret[i] += A[i][j]*b[j]) %= mod;
    return ret;
}

int main(){
    int T = 1;
    int w,n;
    ll h;
    while(cin >>w >>h >>n,w){
        map<ll,vector<int>> obj;
        rep(i,n){
            ll x,y;
            cin >>x >>y;
            --x;
            --y;

            if(y>0){
                obj[y].pb(x);
            }
        }

        mat O(w,vl(w));
        rep(i,w){
            for(int j=-1; j<=1; ++j){
                if(0<=i+j && i+j<w) O[i][i+j] = 1;
            }
        }

        mat A(w,vl(w));
        rep(i,w) A[i][i] = 1;

        ll ny = 0;
        for(const auto &p:obj){

            ll Y = p.fi;
            if(Y - ny > 1) A = mul(mat_pow(O, Y-ny-1), A);

            mat B(O);
            for(int i:p.se){
                for(int j=-1; j<=1; ++j){
                    if(0<=i+j && i+j<w) B[i][i+j] = 0;
                }
            }

            A = mul(B,A);
            ny = Y;
        }

        if(ny != h-1) A = mul(mat_pow(O, h-1-ny), A);

        vector<ll> b(w);
        b[0]=1;

        vector<ll> res = mul(A,b);
        ll ans = res[w-1];
        printf("Case %d: %lld\n", T++, ans);
    }
    return 0;
}



Measured memory_bytes: 3192
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h> // uint64_t

#define max(a,b) ((a) > (b) ? (a) : (b))
#define min(a,b) ((a) > (b) ? (b) : (a))

int get_int(void) {
  int num;
  scanf("%d", &num);
  return num;
}

struct pair {
    int val;
    int idx;
};

// <arr[0]> <arr[1]> .. <arr[size-1]>
int fget_array(struct pair *arr, int size) {
    int i;
    for(i = 0; i < size; i++) {
        scanf("%d", &arr[i].val);
        arr[i].idx = i;
    }
    return 0;
}

#define NUM_MAX 200000

int asc(const void *a1, const void *a2) {
    struct pair *p1 = (struct pair*)a1;
    struct pair *p2 = (struct pair*)a2;
    return p1->val - p2->val;
}

int main(void) {
    int num = get_int();
    static struct pair arr[NUM_MAX];
    fget_array(arr, num);

    qsort(arr, num, sizeof(struct pair), asc);
    int i;
    int ans[NUM_MAX];
    for(i = 0; i < num/2; i++) {
        struct pair p = arr[i];
        ans[p.idx] = arr[num/2].val;
    }
    for(i = num/2; i < num; i++) {
        struct pair p = arr[i];
        ans[p.idx] = arr[num/2 - 1].val;
    }

    for(i = 0; i < num; i++) {
        printf("%d\n", ans[i]);
    }
    return 0;
}

Measured memory_bytes: 4472
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<bitset>
#include<stack>
#include<queue>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<numeric>
#include<set>
#include<math.h>
using namespace std;

const int dx[4]={1,0,-1,0};
const int dy[4]={0,1,0,-1};

#define rep(i,x) for(int i=0;i<x;i++)
#define re(i,x,y) for(int i=x;i<y;i++)

long long INF=1e9;
const int mod=10007;
#define ll long long

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


Measured memory_bytes: 256
N = int(input())
xyh = [list(map(int, input().split())) for i in range(N)]
maxh = 0
minh = 10 ** 9
for i in range(N):
  if xyh[i][2] > maxh:
    maxh = xyh[i][2]
  if xyh[i][2] < minh:
    minh = xyh[i][2]
def hantei(x, y, h):
  for i in range(N):
    if max(h - abs(xyh[i][0] - x) - abs(xyh[i][1] - y), 0) != xyh[i][2]:
      return(False)
  return(True)

def solve():
  for p in range(maxh, minh + 205):
    for q in range(101):
      for r in range(101):
        if hantei(q,r,p) == True:
          return([q,r,p])
print(solve()[0],solve()[1],solve()[2])

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

int main(){
  int n; cin >> n;
  int m; cin >> m;
  vector<int> a(m);
  for (auto &&i : a)
  {
    cin >> i;
  }
  for (int i = 0; i < m; i++)
  {
    if (n >= a.at(i)) n -= a.at(i);
    else 
    {
      cout << -1 << endl;
      return 0;
    }
    
  }
  cout << n << endl;

}

Measured memory_bytes: 3656
#include <bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("-O3")
const int mod = 1e9 + 7;
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(NULL); cout.tie(NULL);
    int n;
    cin>>n;
    vector<vector<int>> matrix(n,vector<int>(n));
    for(int i=0;i<n;i++)
        for(int j=0;j<n;j++)
            cin>>matrix[i][j];
    vector<int> dp(1<<n);
    dp[0] = 1;
    for(int mask = 0; mask<(1<<n)-1; mask++){
        int i = __builtin_popcount(mask);
        for(int j=0;j<n;j++){
            if(matrix[i][j] && !(mask&(1<<j))){
                int mask2 = mask^(1<<j);
                dp[mask2]+=dp[mask];
                if(dp[mask2]>=mod)
                    dp[mask2]-=mod;
            }
        }
    }
    cout<<dp[(1<<n)-1]<<endl;
    return 0;
}

Measured memory_bytes: 8448
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

char s[55][55];
char ans[55][55];

int main() {
  int h, w;
  cin >> h >> w;
  for (int i = 1; i <= h; i++) {
    scanf("%s", s[i] + 1);
  }

  for (int i = 1; i <= h; i++) {
    for (int j = 1; j <= w; j++) {
      if (s[i][j] == '#') {
        ans[i - 1][j - 1] = '#';
      } else {
        ans[i - 1][j - 1] = '0';
        for (int ii = -1; ii <= 1; ii++) {
          for (int jj = -1; jj <= 1; jj++) {
            if (s[i + ii][j + jj] == '#') {
              ans[i - 1][j - 1]++;
            }
          }
        }
      }
    }
  }
  for (int i = 0; i < h; i++) {
    printf("%s\n", ans[i]);
  }
}


Measured memory_bytes: 256