akhauriyash/Code-Regression huggingface dataset:
#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

typedef long long ll;

// const
#define MAX_N 5000
#define MAX_K 5000

// input
int N, K;
ll A[MAX_N];

// variable
bool dp[MAX_N][MAX_K];

ll max(ll a, ll b) { return a > b ? a : b; }

bool need(int i) {
    // initialize dp
    for (int n = 0; n < N; n++)
        for (int k = 0; k < K; k++)
            dp[n][k] = false;
    dp[0][0] = true;

    // calc dp
    int elm_num = 0;
    for (int a_idx = 0; a_idx < N; a_idx++) {
        if (a_idx == i) continue;

        ll a = A[a_idx];

        for (int k = 0; k < K; k++)
            dp[elm_num+1][k] = dp[elm_num][k] || (a <= k && dp[elm_num][k-a]);
        elm_num++;
    }

    for (ll k = max(K-A[i], 0); k < K; k++)
        if (dp[N-1][k]) return true;
    return false;
}

int no_need() {
    sort(A, A+N);

    int l = -1, r = N;
    while (l + 1 < r) {
        int m = (l + r) / 2;
        
        if (need(m)) r = m;
        else l = m;
    }
    return l + 1;
}

int main(int argc, char **argv) {
    cin >> N >> K;

    for (int i = 0; i < N; i++) cin >> A[i];

    int ans = no_need();

    cout << ans << endl;
}


Measured memory_bytes: 24704
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main(){
  ll N, T; cin >> N >> T;
  ll ini = 0, fin = 0, ans = 0;
  for(ll i = 0; i < N; i++){
    ll tmp; cin >> tmp;
    if(tmp <= fin) fin = tmp + T;
    else{
      ans += fin - ini;
      ini = tmp, fin = tmp + T;
    }
  }
  ans += fin - ini;
  cout << ans << endl;
}

Measured memory_bytes: 256
//templates
#include <iostream>
#include <algorithm>
#include <string>
#include <numeric>
#include <vector>
#include <unordered_map>
#include <map>
#include <cmath>
#include <iomanip>
#include <bitset>
#include <sstream>
#define rep(i,n) for(int i = 0; i < (n); i++)
#define ALL(x) (x).begin(),(x).end()
#define sort_key(struct_name,key_name) [](const struct_name &x, const struct_name &y){return x.key_name < y.key_name;}
#define pb(x) push_back(x)
typedef long long ll;
const long long MOD = 1e9 + 7;
using namespace std;

//main
int main(){
    int A,B; cin >> A >> B;
    if((B-1)%(A-1)==0) cout << (B-1)/(A-1) << endl;
    else cout << (B-1)/(A-1)+1 << endl;
}



Measured memory_bytes: 256
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int A = sc.nextInt();
		int B = sc.nextInt();
		int C = sc.nextInt();
		int X = sc.nextInt();
		int count = 0;
		for (int i = 0; i <= A; i++) {
			for (int j = 0; j <= B; j++) {
				for (int k = 0; k <= C; k++) {
					if ((500 * i) + (100 * j) + (50 * k) == X) {
						count++;
					}
				}
			}
		}
		System.out.println(count);
	}
}


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

int main(){
  int n;
  cin >> n;
  int c[n-1],s[n-1],f[n-1];
  rep(i,n-1)cin >> c[i] >> s[i] >> f[i];
  rep(i,n){
    int stop = i;
    int time = 0;
    while(stop<n-1){
      if(time<s[stop]){
        time = s[stop]+c[stop];
      }else{
        int step = (time-s[stop])/f[stop];
        if((time-s[stop])%f[stop]!=0)step++;
        time = s[stop]+f[stop]*step;
        time += c[stop];
        //cout << step << endl;
      }
      stop++;
      //cout << time << endl;
    }
    cout << time << endl;
  }
  return 0;
}


Measured memory_bytes: 256
N = int(input())
count = [0,0,0,0,0]
for i in range(N):
    S = input()
    if S[0] == "M":
        count[0] = count[0] + 1
    if S[0] == "A":
        count[1] = count[1] + 1
    if S[0] == "R":
        count[2] = count[2] + 1
    if S[0] == "C":
        count[3] = count[3] + 1
    if S[0] == "H":
        count[4] = count[4] + 1
a = 0
a = a + count[0]*count[1]*count[2]
a = a + count[0]*count[1]*count[3]
a = a + count[0]*count[1]*count[4]
a = a + count[0]*count[2]*count[3]
a = a + count[0]*count[2]*count[4]
a = a + count[0]*count[3]*count[4]
a = a + count[1]*count[2]*count[3]
a = a + count[1]*count[2]*count[4]
a = a + count[1]*count[3]*count[4]
a = a + count[2]*count[3]*count[4]
print(a)

Measured memory_bytes: 3188
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <vector>
#include <numeric>
#include <string.h>
using namespace std;
typedef long long int lli;
#define urept(soeji, start, n) for (int soeji = start; soeji < n; soeji++)
#define drept(soeji, start, n) for (int soeji = start; soeji > n; soeji--)
struct drink
{
    lli A;
    lli B;
};
int main(void)
{
    int N, M;
    cin >> N >> M;
    drink *D;
    D = new drink[N];
    urept(i, 0, N)
    {
        cin >> D[i].A >> D[i].B;
    }
    sort(D, D + N, [](const drink &x, const drink &y) { return x.A < y.A; });
    lli sum = 0;
    int count = 0;
    urept(i, 0, N)
    {
        for (int j = 0; j < D[i].B; j++)
        {
            if (count == M)
            {
                break;
            }            
          	sum += (D[i].A);
            count += 1;
        }
    }
    cout << sum << endl;
    return 0;
}

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

#define REP(i,num) for(int i=0;i<(num);++i)
#define ALL(c) c.begin(),c.end()
#define LOOP(i) while(i--)
#define PRINTALL(c) for(auto& x:c){cout<<x<<' ';}cout<<endl;
#define PAIRCOMP(c,comp) [](const pair<ll,ll>& lhs,const pair<ll,ll>& rhs){return lhs.c comp rhs.c;}

using namespace std;
using ll = long long;

constexpr ll atcoder_mod = 1e9+7;

template<typename T=int>
T in(){T x; cin >> x; return (x);}
template<typename T=int,typename C=vector<T>>
C vecin(int N){C x(N);REP(i,N){x[i]=in<T>();}return move(x);}

void vout(){cout << endl;}
template<typename Head,typename... Tail>
void vout(Head&& h,Tail&&... t){cout << ' ' << h;vout(forward<Tail>(t)...);}
void out(){cout << endl;}
template<typename Head,typename... Tail>
void out(Head&& h,Tail&&... t){cout << h;vout(forward<Tail>(t)...);}

int main(){
	cin.tie(0);
	ios::sync_with_stdio(false);
	cout<<fixed<<setprecision(10);

	ll N=in();
	string S=in<string>(),T=in<string>();
	vector<int> B(1,0);
	for(int i=0;i<N;){
		if(S[i]==T[i]){
			B.push_back(1);
			i++;
		}
		else{
			B.push_back(2);
			i+=2;
		}
	}
	
	ll sum=1;
	int M=B.size()-1;
	REP(i,M){
		if(B[i+1]==2){
			if(B[i]==1){
				sum *= 2LL;
				sum%=atcoder_mod;
			}
			else if(B[i]==2){
				sum *= 3LL;
				sum%=atcoder_mod;
			}
			else{
				sum *= 6LL;
				sum%=atcoder_mod;
			}
		}
		else{
			if(B[i]==0){
				sum *= 3LL;
				sum%=atcoder_mod;
			}
			else if(B[i]==1){
				sum *= 2LL;
				sum%=atcoder_mod;
			}
		}
	}
	out(sum);
	return 0;
}


Measured memory_bytes: 256
#include<vector>
#include<iostream>
#include<algorithm>
using namespace std;

struct node {
  long long ddl,take;
  node(long long a,long long b){
    take = a;
    ddl = b;
  }
  bool operator < (const node other)const{
    return ddl < other.ddl;
  }
};

int main(){
  int n;
  cin>>n;
  
  vector<node> tasks;
  int take,ddl;
  for(int i=0;i<n;++i){
    cin>>take>>ddl;
    tasks.push_back(node(take,ddl));
  }
  
  sort(tasks.begin(),tasks.end());
  
  long long curr = 0;
  bool ok = true;
  for(int i=0;i<n;++i){
    if(curr + tasks[i].take > tasks[i].ddl){
      ok = false;
      break;
    } else {
      curr = curr + tasks[i].take;
    }
  }
  
  if(ok){
    cout<<"Yes"<<endl;
  } else {
    cout<<"No"<<endl;
  }
  
  return 0;
}

Measured memory_bytes: 6512
#include <bits/stdc++.h>
#define rep(i,n) for(int i = 0; i < n; i++)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int MAX_N = 100005;
int h[MAX_N];
int dp[MAX_N];

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

	dp[0] = 0;
	dp[1] = abs(h[0] - h[1]);
	for (int i = 2; i < N; ++i)
	{
		dp[i] = min(dp[i-2] + abs(h[i] - h[i-2]), dp[i-1] + abs(h[i] - h[i-1]));
	}
	cout << dp[N-1] << endl;
	return 0;
}

Measured memory_bytes: 1024
#include <iostream>
#include <algorithm>
#include <iomanip>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <numeric>
#include <bitset>
#include <cmath>

static const int MOD = 1000000007;
using ll = long long;
using u32 = unsigned;
using u64 = unsigned long long;
using namespace std;

template<class T> constexpr T INF = ::numeric_limits<T>::max()/32*15+208;

int main() {
    string s;
    cin >> s;
    for (auto &&i : s) {
        if(i == '7'){
            puts("Yes");
            return 0;
        }
    }
    puts("No");
    return 0;
}

Measured memory_bytes: 3624
def bi(l,x):
    ok = len(l)
    ng = -1
    while ok-ng > 1:
        mid = (ng+ok)//2
        if l[mid] < x:
            ok = mid
        else:
            ng = mid
    return ok

n = int(input())
a = [int(input()) for _ in range(n)]
t = [-1]
m = 1
for x in a:
    c = bi(t,x) 
    if c == m:
        t.append(x)
        m += 1
    else:
        t[c] = x
print(m)


Measured memory_bytes: 7836
#include<iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <tuple>
#include <cmath>
#include <queue>
#include <map>


using namespace std;


int main()
{
  long n, m, x;
  cin >> n >> m >> x;
  vector <long> a(m);
  vector <bool> b(n + 1, false);

  for (int i = 0; i < m; i++) {
    cin >> a[i];
    b[a[i]] = true;
  }

  //mの偶数奇数で

  long maxcost = 10000000;
  long cost = 0;
  for (int i = x; i < n + 1; i++) {
    if (b[i] == true)cost++;
  }
  if (maxcost > cost)maxcost = cost;
  cost = 0;

  for (int i = x; i >= 0; i--) {
    if (b[i] == true)cost++;
  }
    if (maxcost > cost)maxcost = cost;


  cout << maxcost << endl;


  return 0;
}

Measured memory_bytes: 256
#[allow(unused_macros)]
macro_rules! input {
	(source = $s:expr, $($r:tt)*) => {
		let mut iter = $s.split_whitespace();
		input_inner!{iter, $($r)*}
	};
	($($r:tt)*) => {
		let s = {
			use std::io::Read;
			let mut s = String::new();
			std::io::stdin().read_to_string(&mut s).unwrap();
			s
		};
		let mut iter = s.split_whitespace();
		input_inner!{iter, $($r)*}
	};
}
#[allow(unused_macros)]
macro_rules! input_inner {
	($iter:expr) => {};
	($iter:expr, ) => {};

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

	($iter:expr, [ $t:tt ; $len:expr ]) => {
		(0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
	};

	($iter:expr, chars) => {
		read_value!($iter, String).chars().collect::<Vec<char>>()
	};

	($iter:expr, usize1) => {
		read_value!($iter, usize) - 1
	};

	($iter:expr, $t:ty) => {
		$iter.next().unwrap().parse::<$t>().expect("Parse error")
	};
}

fn gcd(a: i64, b: i64) -> i64 {
	if b == 0 { a }
	else 	{ gcd(b, a%b) }
}

fn dfs(s: usize, graph: &Vec<Vec<usize>>, used: &mut Vec<bool>) {
	used[s] = true;
	for g in &graph[s] {
		if !used[*g] { 
			dfs(*g, graph, used);
		}
	}
}

fn main(){
	input! {
		a: i64,
		b: i64,
	}
	let mut ab = gcd(a, b);
	let mut i = 2;
	let mut ans = 1;
	'outer: while i*i <= ab {
		if ab%i == 0 {
			ans += 1;
			while ab%i == 0 {
				ab /= i;
				if ab == 1 { break 'outer; }
			}
		}
		i += 1;
	}
	if ab != 1 { ans += 1; }
	println!("{}", ans);
	// let mut comv = Vec::new();
	// let mut i = 1;
	// while i*i <= a && i*i <= b { 
	// 	if a%i == 0 && b%i == 0 { 
	// 		comv.push(i); 
	// 		if i != a/i && b%(a/i) == 0{
	// 			comv.push(a/i); 
	// 		}
	// 	}
	// 	i += 1;
	// }
	// let mut graph = vec![vec![]; comv.len()];
	// for i in 0..comv.len() {
	// 	for j in i+1..comv.len() { 
	// 		if gcd(comv[i], comv[j]) == 1 {
	// 			graph[i].push(j);
	// 			graph[j].push(i);
	// 		}
	// 	}
	// }
	// let mut ans = 0;
	// let mut used = vec![false; comv.len()];
	// for i in 0..comv.len() {
	// 	if !used[i] {
	// 		dfs(i, &graph, &mut used);
	// 		ans += 1;
	// 	}
	// }
	// println!("{}", ans);
	// println!("{:?}", comv);
	// println!("{:?}", graph);
}

Measured memory_bytes: 4352
n = input()
a = int(n[0])
b = int(n[1])
c = int(n[2])
d = int(n[3])

if a+b+c+d == 7:
    print('{}+{}+{}+{}=7'.format(a, b, c, d))
elif a+b+c-d == 7:
    print('{}+{}+{}-{}=7'.format(a, b, c, d))
elif a+b-c+d == 7:
    print('{}+{}-{}+{}=7'.format(a, b, c, d))
elif a+b-c-d == 7:
    print('{}+{}-{}-{}=7'.format(a, b, c, d))
elif a-b+c+d == 7:
    print('{}-{}+{}+{}=7'.format(a, b, c, d))
elif a-b+c-d == 7:
    print('{}-{}+{}-{}=7'.format(a, b, c, d))
elif a-b-c+d == 7:
    print('{}-{}-{}+{}=7'.format(a, b, c, d))
elif a-b-c-d == 7:
    print('{}-{}-{}-{}=7'.format(a, b, c, d))

Measured memory_bytes: 3064
#include<iostream>
#include<vector>
#include<algorithm>
#include<string>
#include<numeric>
#include<utility>

using namespace std;

typedef long long int ll;
const int INF = 1<<30;
const long long LINF = 1LL<<60;

ll n, k;

bool check(ll x, vector<ll> &a, vector<ll> &f){
    ll cnt = 0;
    for(int i = 0; i < n; i++){
        ll t = a[i] * f[i];
        if(t > x){
            t -= x;
            cnt += (t + f[i] - 1) / f[i];
        }
    }
    return cnt <= k;
}

int main(){
    cin >> n >> k;
    vector<ll> a(n), f(n);
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    for(int i = 0; i < n; i++){
        cin >> f[i];
    }
    sort(begin(a), end(a));
    sort(rbegin(f), rend(f));
    ll ok = (ll)1e12, ng = -1;
    while(ok - ng > 1){
        ll mid = (ok + ng) / 2;
        if(check(mid, a, f)){
            ok = mid;
        }else{
            ng = mid;
        }
    }
    cout << ok <<endl;
    return 0;
}


Measured memory_bytes: 3328
import java.util.Scanner;

public class Main {
	public static void main(String[]args){
		Scanner sc=new Scanner(System.in);
		int n=sc.nextInt();
		long[] N=new long[n];
		long h,max=-1000000,min=1000000,sum=0;
		for(int i=0;i<n;i++){
			h=sc.nextInt();
			N[i]=h;
			sum+=N[i];
			if(N[i]<min)
				min=N[i];
			if(N[i]>max)
				max=N[i];
		}
		System.out.println(min+" "+max+" "+sum);
	}
}


Measured memory_bytes: 41808
# import sys
# import math #sqrt,gcd,pi
# import decimal
# import queue # queue
# import bisect
# import heapq # priolity-queue
# import time
# from itertools import product,permutations,\
#     combinations,combinations_with_replacement
# 重複あり順列、順列、組み合わせ、重複あり組み合わせ
# import collections # deque
# from operator import itemgetter,mul
# from fractions import Fraction
# from functools import reduce

mod = int(1e9+7)
INF = 1<<29
lINF = 1<<35

def readInt():
    return list(map(int,input().split()))

def main():
    s = input()
    ans = 0
    for i in range(len(s)):
        if s[i]=="+":
            ans += 1
        else:
            ans -= 1
    print(ans)
    return

if __name__=='__main__':
    main()

Measured memory_bytes: 3064
def main():
    N, M = (int(i) for i in input().split())
    G = [[] for _ in range(N)]
    deg = [0]*N
    for _ in range(M):
        a, b = (int(i) for i in input().split())
        G[a].append(b)
        deg[b] += 1

    from collections import deque

    def topological_sort():
        que = deque()
        ans = []*N
        for i in range(N):
            if deg[i] == 0:
                que.append(i)
                ans.append(i)

        while que:
            u = que.popleft()
            for v in G[u]:
                deg[v] -= 1
                if deg[v] == 0:
                    que.append(v)
                    ans.append(v)
        return ans

    print(*topological_sort(), sep="\n")


if __name__ == '__main__':
    main()



Measured memory_bytes: 9248
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading;

class Program
{
    static int INF = 10000000;
    static void Main(string[] args)
    {
        int keta = 1;
        int nextKeta = 10;
        int n = int.Parse(Console.ReadLine());
        var dic = new Dictionary<(int x , int y),int>();
        for(int i = 1; i <= n; i++)
        {
            if(i == nextKeta)
            {
                keta *= 10;
                nextKeta *= 10;
            }
            int a = i / keta;
            int b = i % 10;
            if (!dic.ContainsKey((a , b)))dic.Add((a, b), 1);
            else dic[(a,b)]++;
        }
        int sum = 0;
        foreach(var ele in dic.Keys)
        {
            int x = ele.y;
            int y = ele.x;
            if (!dic.ContainsKey((x,y)))continue;
            sum += dic[ele] * dic[(x,y)];
        }
        Console.WriteLine(sum);
    }

}

   

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

using namespace std;
typedef long long ll;
typedef pair<int,int> P;

//マクロ
#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=(ll)(n)-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=(a);i<=(b);i++)
#define FORD(i,a,b) for(ll i=(a);i>=(b);i--)
#define ALL(x) (x).begin(),(x).end() //sortなどの引数を省略したい
#define SIZE(x) ((ll)(x).size()) //sizeをsize_tからllに直しておく
#define MAX(x) *max_element(ALL(x))
#define INF 1000000000000 //10^12
#define MOD 10000007 //10^9+7
#define PB push_back
#define MP make_pair
#define F first
#define S second

int main(int argc, char const *argv[]) {
    int r;
    cin >> r;
    ll ans = pow(r,2) * 3;
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string>
#include<vector>
#include<queue>
#include<deque>
using namespace std;
typedef pair<int, int>P;
typedef pair<int, pair < int, int > > PP;
typedef long long ll;
ll inf = -1;
ll mod = pow(10, 9) + 7;
 long long lcm(long long a, long long b) {
	long long old_old_a = a, old_old_b = b;
	long long old_a, old_b;
	while (b != 0) {
		old_a = a;
		a = b;
		old_b = b;
		b = old_a % b;
	}
	long long g = old_b;
	return old_old_a / g * old_old_b;
}
int main() {
	ll a,b,c,d;
	cin>>a>>b>>c>>d;
	a--;
	ll k=lcm(c,d);
	cout<<b-a-((b/c-a/c)+(b/d-a/d)-(b/(k)-a/(k)))
	<<endl;
	return 0;
}

Measured memory_bytes: 256
def gcd(a, b):
    """a, bの最大公約数(greatest common divisor:GCD)を求める"""
    if b == 0:
        return a
    return gcd(b, a%b)

def make_prime_factors2(n):
    """自然数nの素因数を列挙した圧縮済みリストを出力する
    計算量：O(sqrt(N))
    入出力例：156 -> [(2, 2), (3, 1), (13, 1)]
    """
    prime_factors = []
    for k in range(2, int(n**0.5) + 1):
        cnt = 0
        while n % k == 0:
            cnt += 1
            n = n // k
        if cnt != 0:
            prime_factors.append((k, cnt))
    if n != 1:
        prime_factors.append((n, 1))
    return prime_factors
  
a, b = map(int, input().split())
max_gcd = gcd(a, b)
li = make_prime_factors2(max_gcd)
print(len(li) + 1)

Measured memory_bytes: 38768
import sys
import math
from collections import defaultdict
from bisect import bisect_left, bisect_right

sys.setrecursionlimit(10**7)
def input():
    return sys.stdin.readline()[:-1]

mod = 10**9 + 7

def I(): return int(input())
def LI(): return list(map(int, input().split()))
def LIR(row,col):
    if row <= 0:
        return [[] for _ in range(col)]
    elif col == 1:
        return [I() for _ in range(row)]
    else:
        read_all = [LI() for _ in range(row)]
        return map(list, zip(*read_all))

#################

N,Q = LI()

a = [N-1]*N  # 各行の白石の最左
b = [N-1]*N  # 各列の白石の最上

a[-1] = 0
b[-1] = 0

x1 = N-1  # 枠の縦位置
x2 = N-1  # 枠の横位置

ans = (N-2)**2
for i in range(Q):
    j,k = LI()
    k -= 1
    if j == 1:
        if k > x2:
            ans -= (b[k]-1)
        else:
            for n in range(k+1,x2):
                b[n] = x1
            ans -= max(0,(x1-1))
            x2 = k
    else:
        if k > x1:
            ans -= (a[k]-1)
        else:
            for n in range(k+1,x1):
                a[n] = x2
            ans -= max(0,(x2-1))
            x1 = k

print(ans)

Measured memory_bytes: 77884
#include<bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define rep(i, j, k) for (auto i = j; i < k; i++)
#define rrep(i, j, k) for (auto i = j; i > k; i--)
using namespace std;

void solve(ll &n) {
  rrep(len, 100000LL, 0LL) {
    ll tmp = n - len * (len - 1) / 2;
    if (tmp <= 0) continue;
    if (tmp % len == 0) {
      ll a = tmp / len;
      cout << a << " " << len << endl;
      return;
    }
  }
}

int main() {
  ll n;
  while (cin >> n, n) solve(n);
}



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

char judge(char , char);

int main(void) {

    string T;

    cin >> T;

    for (int i = 0; i < T.length(); i++) {

        if (T[i] == '?') {
            char pre, post;
            if (i != 0) { pre = T[i - 1]; }
            else { pre = 'b'; }

            if (i != T.length() - 1) { post = T[i + 1]; }
            else { post = 'a'; }

            char change = judge(pre, post);            

            T[i] = change;

        }
    }

    cout << T;

    return 0;

}

char judge(char pre, char post) {

    if (pre == 'D' && post == 'D') return 'P';
    else if (pre == 'D' && post == 'P') return 'D';
    else if (pre == 'D' && post == '?') return 'P';
    else if (pre == 'D' && post == 'a') return 'D';
    
    return 'D';
}

Measured memory_bytes: 3356
def main():
    n,m = map(int, input().split())
    h = list(map(int, input().split()))
    ab = {}
    for _ in range(m):
        a,b = map(int, input().split())
        ab[a] = ab.get(a, set())
        ab[a].add(b)
        
        ab[b] = ab.get(b, set())
        ab[b].add(a)

    ans = set()
    for num, val in enumerate(h,1):
        is_top = True
        if (tenbodai := ab.get(num, [])):
            for i in tenbodai:
                if val <= h[i-1]: is_top = False
        if is_top: ans.add(num)
    print(len(ans))
if __name__ == "__main__":
    main()

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

int main(){
 	
  int n;
  cin>>n;
  
  int a[n],b[n],c[n];
  
  for(int i=0;i<n;i++)
      cin>>a[i]>>b[i]>>c[i];
  
  int dp[n][3];
  
  memset(dp,0,sizeof dp);
  
  dp[0][0] = a[0];
  dp[0][1] = b[0];
  dp[0][2] = c[0];
 
  for(int i=1;i<n;i++){
    for(int j=0;j<3;j++)
      for(int k = 0;k<3;k++)
        if(j!=k)
          dp[i][j] = max(dp[i][j],dp[i-1][k]+(j==0?a[i]:(j==1?b[i]:c[i]))); 
  }
  
  cout<<max(dp[n-1][0],max(dp[n-1][1],dp[n-1][2]));
}


Measured memory_bytes: 2560
use proconio::{input, fastout};

macro_rules! echo {
  ($val:expr) => {
    println!("{}", $val);
  }
}

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

  let mut aa = aa;
  aa.sort();
  let mut cusum = Vec::with_capacity(n+1);
  cusum.push(0);
  for &a in &aa {
    let last = *cusum.last().unwrap();
    cusum.push(last + a);
  }
  let mut pos = 0;
  for i in 1..n+1 {
    if cusum[i-1] * 2 >= (cusum[i] - cusum[i-1]) {
      continue
    } else {
      pos = i;
    }
  }
  echo!(n-pos+1);
}


Measured memory_bytes: 4572
#include <bits/stdc++.h>
using namespace std;
bool ans(const vector<string>& W){
	const int n=W.size();
	for (int i=0;i<n-1;i++){
		if (W[i].back()!=W[i+1].front())
			return false;
	    for (int j=i+1;j<n;j++){
	    	if (W[i]==W[j])
				return false;
		}
	}
	return true;
}
int main(){
	int n;
	cin>>n;
	vector<string> W(n);
	for (int i=0;i<n;++i){
		cin>>W[i];
	}
	if(ans(W))
		cout<<"Yes"<<endl;
	else
		cout<<"No"<<endl;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define P pair<ll, ll>
#define Graph vector<vector<P>>
#define fi first
#define se second
constexpr ll mod = 1000000007;
constexpr ll INF = (1ll << 60);
constexpr double pi = 3.14159265358979323846;
template <typename T>inline bool chmax(T &a, T b){if (a < b){a = b;return 1;}return 0;}
template <typename T>inline bool chmin(T &a, T b){if (a > b){a = b;return 1;}return 0;}

int main(){
    string s,t;cin>>s>>t;
    ll ans=0;
    rep(i,3) if(s[i]==t[i]) ans++;

    cout<<ans<<endl;
    return 0;
}

Measured memory_bytes: 3496
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n)  for(long long i=0;i<(long long)(n);i++)
#define REP(i,k,n) for(long long i=k;i<(long long)(n);i++)
#define all(a) a.begin(),a.end()
#define pb push_back
#define eb emplace_back
#define lb(v,k) (lower_bound(all(v),k)-v.begin())
#define ub(v,k) (upper_bound(all(v),k)-v.begin())
#define fi first
#define se second
#define pi M_PI
typedef long long ll;
typedef pair<ll,ll> P;
typedef tuple<ll,ll,ll> PP;
typedef multiset<ll> S;
typedef priority_queue<ll> PQ;
typedef priority_queue<P,vector<P>,greater<P>> SPQ;
using vi=vector<ll>;
using vvi=vector<vi>;
using vvvi=vector<vvi>;
const ll inf=1001001001001001;
const int INF=1001001001;
const int mod=1000000007;
template<class T> bool chmin(T&a,T b){if(a>b){a=b;return true;}return false;}
template<class T> bool chmax(T&a,T b){if(a<b){a=b;return true;}return false;}
template<class T> void out(T a){cout<<a<<endl;}
template<class T> void outp(T a){cout<<'('<<a.fi<<','<<a.se<<')'<<endl;}
template<class T> void outvp(T v){rep(i,v.size())outp(v[i]);}
template<class T> void outv(T v){rep(i,v.size()){if(i)cout<<' ';cout<<v[i];}cout<<endl;}
template<class T> void outvv(T v){rep(i,v.size()){rep(j,v[i].size()){if(j)cout<<' ';cout<<v[i][j];}cout<<endl;}}
ll gcd(ll a,ll b){
    if(b==0)return a;
    return gcd(b,a%b);
}
ll modpow(ll a,ll b){
    a%=mod;
    if(b==0)return 1;
    if(b&1)return a*modpow(a,b-1)%mod;
    ll k=modpow(a,b/2);
    return k*k%mod;
}
int main(){
    ll n,ans=inf;cin>>n;
    vi v(n);
    rep(i,n)cin>>v[i];
    REP(k,1,101){
        ll sum=0;
        rep(i,n)sum+=(v[i]-k)*(v[i]-k);
        chmin(ans,sum);
    }
    out(ans);
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define REPR(i,n) for(int i=n; i>-1; --i)
#define ALL(a) (a).begin(),(a).end()
#define INIT(a,n,x); REP(i,(n)){ (a)[i]=(x); }
#define CINA(a,n); REP(i,(n)){ cin >> (a)[i]; }
#define INIT2(a,n,m,x); REP(i,(n)){ REP(j,(m)){(a)[i][j]=(x);} }
#define CINA2(a,n,m); REP(i,(n)){ REP(j,(m)){cin >> (a)[i][j];} }
#define Liny "Yes\n"
#define Linn "No\n"
#define LINY "YES\n"
#define LINN "NO\n"

int main(){
  ll N; cin>>N;
  map<string,ll> mp;
  vector<string> v;
  string s;
  REP(i,N){
    cin >> s;
    sort(ALL(s));
    if(mp[s]==0){v.push_back(s);}
    mp[s]++;
  }
  ll r=0;
  for(string c:v){
    ll t = mp[c];
    r += t*(t-1)/2;
  }
  cout <<r;
}

Measured memory_bytes: 16628
#include <bits/stdc++.h>
#include <map>
#include <cmath>
typedef long long int ll;
using namespace std; 
int main(){
	ios_base::sync_with_stdio(false);  
	cin.tie(NULL);
	int h,a;cin>>h>>a;
	ll p = h/a;
	if(p*a<h){
		p++;
	}
	cout<<p<<endl;
}


Measured memory_bytes: 256
def main():
    n=int(input())
    nn=2*n-1
    s=[input() for _ in [0]*n]
    s=[i+i[:-1] for i in s]+[i+i[:-1] for i in s][:-1]
    ans=[[0]*n for _ in [0]*n]
    for i in range(1,nn):
        m=min(i+1,n)
        for j in range(nn-1):
            for k in range(max(i-j-n,0)+1,min(m,nn-j,i-j+n)):
                ii=i-k
                if s[i][j]!=s[ii][j+k]:
                    l=min(n-k+1,ii,j)
                    width=l-max(-1,ii-n,j-n)
                    ans[ii-l][j-l]=max(ans[ii-l][j-l],width)
    for i in range(1,n):
        for j in range(1,n):
            ans[i][j]=max(ans[i][j],ans[i-1][j-1]-1)
    print(sum([sum([i==0 for i in a]) for a in ans]))
main()

Measured memory_bytes: 54748
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main(void){
    int n,sum=0;
    cin>>n;
    // Your code here!
    vector<int> s(n,0);
    for(int i=0;i<n;i++){
        cin>>s[i];
        sum+=s[i];
    }
    sort(s.begin(),s.end(),greater<int>());
    if(sum%10!=0) {
        cout<<sum<<endl;
        return 0;
    }
    else {
        for(int i=0;i<n;i++){
            if(s[n-i-1]%10!=0){
        sum=sum-s[n-i-1];
         if(sum%10!=0) {
             cout<<sum<<endl;
             return 0;
         }
            }
    }
}
cout<<"0"<<endl;
return 0;
}

Measured memory_bytes: 256
#include "iostream"
#include "algorithm"
#include "string"
using namespace std;

int main() {
	int n, m;
	cin >> n >> m;
	int atari, hazure;
	int maxCost = 0, cost = 0;
	for (int i = 0; i < m; i++) {
		cin >> atari >> hazure;
		if (atari < hazure) {
			cost += n - atari;
			if (n - atari > maxCost) {
				maxCost = n - atari;
			}
		}
	}
	int ans = cost - maxCost;
	cout << ans << endl;
}


Measured memory_bytes: 3104
n, a, b = map(int, input().split())
mod = pow(10, 9) + 7

def comb(N, x):
    numerator = 1
    for i in range(N-x+1, N+1):
        numerator = numerator * i % mod
    denominator = 1
    for j in range(1, x+1):
        denominator = denominator * j % mod
    d = pow(denominator, mod-2, mod)
    return numerator * d

a = comb(n, a)
b = comb(n, b)

print((pow(2, n, mod) -1 -a -b) % mod)

Measured memory_bytes: 3064
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
use std::io::{Write, BufWriter};
// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
macro_rules! input {
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

    ($next:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    };

    ($next:expr, chars) => {
        read_value!($next, String).chars().collect::<Vec<char>>()
    };

    ($next:expr, usize1) => {
        read_value!($next, usize) - 1
    };

    ($next:expr, [ $t:tt ]) => {{
        let len = read_value!($next, usize);
        (0..len).map(|_| read_value!($next, $t)).collect::<Vec<_>>()
    }};

    ($next:expr, $t:ty) => {
        $next().parse::<$t>().expect("Parse error")
    };
}

fn solve() {
    let out = std::io::stdout();
    let mut out = BufWriter::new(out.lock());
    macro_rules! puts {
        ($($format:tt)*) => (write!(out,$($format)*).unwrap());
    }
    input! {
        ab: [(usize1, usize1); 3],
    }
    let mut deg = vec![0; 4];
    for (a, b) in ab {
        deg[a] += 1;
        deg[b] += 1;
    }
    for i in 0..4 {
        if deg[i] > 2 {
            puts!("NO\n");
            return;
        }
    }
    puts!("YES\n");
}

fn main() {
    // In order to avoid potential stack overflow, spawn a new thread.
    let stack_size = 104_857_600; // 100 MB
    let thd = std::thread::Builder::new().stack_size(stack_size);
    thd.spawn(|| solve()).unwrap().join().unwrap();
}


Measured memory_bytes: 8572
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = list(map(int, input().split()))
tmp = float("inf")
ans = 0
for i in a:
    ans += b[i - 1]
    if tmp == i - 1:
        ans += c[tmp - 1]
    tmp = i
print(ans)


Measured memory_bytes: 3060
def factorization(n):
    arr = []
    temp = n
    for i in range(2, int(-(-n**0.5//1))+1):
        if temp%i==0:
            cnt=0
            while temp%i==0:
                cnt+=1
                temp //= i
            arr.append([i, cnt])

    if temp!=1:
        arr.append([temp, 1])

    if arr==[]:
        arr.append([n, 1])

    return arr


N, P = map(int, input().split())

prime = factorization(P)
ans = 1
for p, n in prime:
    if n >= N:
        ans *= p ** (n // N)
        
print(ans)


Measured memory_bytes: 9456
#include <bits/stdc++.h>
using namespace std;
#define rep(i, k, n) for(int i = (int)(k);i < (int)(n);i++)
int main() {
  int N, M, a, b;cin >> N >> M;
  vector<int> v(N, -1);
  vector<vector<int>> w(N);
  queue<int> q;
  rep(i, 0, M) {
    cin >> a >> b;
    a--;b--;
    w[a].push_back(b);
    w[b].push_back(a);
  }
  q.push(0);
  while(q.size() != 0) {
    a = q.front();q.pop();
    for(auto na : w[a]) if(v[na] == -1) {
      v[na] = a+1;
      q.push(na);
    }
  }
  cout << "Yes" << endl;
  rep(i, 1, N) cout << v[i] << endl;
}

Measured memory_bytes: 10148
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const ll INF=(ll)1e9;
const ll MOD=(ll)1e9+7;
vector<int> dx={1,0,-1,0},dy={0,1,0,-1};

int main(){
  ll N,M;
  cin>>N>>M;
  ll A[M];
  vector<ll> B(N+1,0);
  B[0]++;
  set<ll> s;
  for(ll i=0;i<M;i++){
    cin>>A[i];
    s.insert(A[i]);
  }
  if(!s.count(1)) B[1]++;
  for(ll i=2;i<=N;i++){
    if(!s.count(i-2)&&!s.count(i-1)) B[i]=B[i-2]%MOD+B[i-1]%MOD;
    else if(!s.count(i-2)) B[i]=B[i-2]%MOD;
    else if(!s.count(i-1)) B[i]=B[i-1]%MOD;
    B[i]%=MOD;
  }
  cout<<B[N]<<endl;
}


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

using namespace std;
#define int long long
#define pb push_back
#define fio ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define vin(vec) for(auto &elem:vec)cin>>elem
#define vi vector<int>
template<class L,class R> ostream& operator<<(ostream& cout,pair<L, R> P)
{return cout<<'('<<P.first<<','<< P.second<<')';}
template<class T> ostream& operator<<(ostream& cout,vector<T> V)
{cout<<"[ ";for(auto v:V)cout<<v<<' ';return cout<<']';}
#define show(x) cout<<#x<<" : "<<x<<'\n';


signed main(){
	fio;
	int t=1;
	// cin>>t;
	while(t--){
		int n;
		cin>>n;
		vector<int> v(n, 0);
		vin(v);
		vector<int> dp(n, 0);
		dp[n-1]=0;
		dp[n-2]=abs(v[n-1]-v[n-2]);
		for(int i=n-3; i>=0; i--){
			dp[i]=min(dp[i+1] + abs(v[i]-v[i+1]), dp[i+2]+abs(v[i]-v[i+2]));
		}
		cout<<dp[0]<<'\n';
	}
}

Measured memory_bytes: 4788
H, W = [int(_) for _ in input().split()]
C = [[int(_) for _ in input().split()] for _ in range(10)]
A = [[int(_) for _ in input().split()] for _ in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            C[i][1] = min(C[i][1], C[i][j] + C[j][1])

ans = 0
for h in range(H):
    for w in range(W):
        if A[h][w] != -1:
            v = A[h][w]
            ans += C[v][1]
print(ans)


Measured memory_bytes: 9552
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<ll, ll> P;
typedef vector<ll> VI;
typedef vector<VI> VVI;
const ll MOD = 998244353;
const ll INF = 4611686018427387903;
#define REP(i, n) for (int i = 0; i < n; i++)
#define ALL(v) v.begin(), v.end()

ll power(ll x, ll y) {
	if (y==0) return 1;
	else if (y==1) return x%MOD;
	else if (y%2==0) { ll pow=power(x,y/2); return (pow*pow)%MOD; } 
	else { ll pow=power(x,y/2); return ((pow*pow)%MOD)*x%MOD; }
}
ll divid(ll x, ll y) {
	return ((x%MOD)*power(y,MOD-2))%MOD;
}

int main(){
	int n, s; cin >> n >> s;
	VI a(n); REP(i,n) cin >> a[i];
	VVI dp(n+1,VI(s+1,0));
	dp[0][0]=power(2,n);
	REP(i,n){
		REP(j,s+1){
			dp[i+1][j]=dp[i][j];
			if(j-a[i]>=0)
				dp[i+1][j]+=divid(dp[i][j-a[i]],2);
			dp[i+1][j]%=MOD;
		}
	}
	cout << dp[n][s] << endl;
	return 0;
}


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

#define pb push_back
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define debug(x)  cerr << #x << " = " << x << endl
using namespace std;

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

const ld PI = 3.14159265359;

const ll MOD = (ll) 998244353ll;
const ll MAXN = (ll) 2e5 + 10;
const ll INF = (ll) 2242545357980376863;
const ld EPS = (ld) 1e-8;



int main(){
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	ll n, a, b, ans = 0;
	 cin >> n;
	str s,t, r;
	cin >> s >> t >> r;
	set<char> st;
	for(int i = 0; i< n;i++){
		st.clear();
		st.insert(s[i]);
		st.insert(t[i]);
		st.insert(r[i]);
		ans += (st.size() - 1);
	}
	cout << ans;
	return 0;
}


/*

                                 ____              ,----..               ,----..
   ,---,                       ,'  , `.           /   /   \             /   /   \
  '  .' \                   ,-+-,.' _ |          /   .     :           /   .     :
 /  ;    '.              ,-+-. ;   , ||         .   /   ;.  \         .   /   ;.  \
:  :       \            ,--.'|'   |  ;|        .   ;   /  ` ;        .   ;   /  ` ;
:  |   /\   \          |   |  ,', |  ':        ;   |  ; \ ; |        ;   |  ; \ ; |
|  :  ' ;.   :         |   | /  | |  ||        |   :  | ; | '        |   :  | ; | '
|  |  ;/  \   \        '   | :  | :  |,        .   |  ' ' ' :        .   |  ' ' ' :
'  :  | \  \ ,'        ;   . |  ; |--'         '   ;  \; /  |        '   ;  \; /  |
|  |  '  '--'          |   : |  | ,             \   \  ',  /          \   \  ',  /
|  :  :                |   : '  |/               ;   :    /            ;   :    /
|  | ,'                ;   | |`-'                 \   \ .'              \   \ .'
`--''                  |   ;/                      `---`                 `---`
                       '---'

*/


Measured memory_bytes: 256
#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']
require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

#exec({'RUBY_THREAD_VM_STACK_SIZE'=>'100000000'},'/usr/bin/ruby', $0) if !ENV['RUBY_THREAD_VM_STACK_SIZE']
require 'prime'

def inpf() a=gets.chomp.split(" ").map(&:to_f)end

def inps() a=gets.chomp.split(" ")end

def copy(a) Marshal.load(Marshal.dump(a)) end

def kaijo(n,r = 10**9+7)(n < 2)? 1 : (2..n).inject{|memo,u|memo=(memo*u)%r} end

def na(n,d=0) Array.new(n,d)end

def na2(n,m,d=0) Array.new(n){Array.new(m,d)}end

def na3(n,m,l,d=0) Array.new(n){Array.new(m){Array.new(l,d)}}end

def inp() a=gets.chomp.split(" ").map(&:to_i)end

def r_up(a, b) (a+b-1)/b end

def sum(a) a.inject(:+) end

def big(a,b) return (a>b)? a:b end

def small(a,b) return (a<b)? a:b end

a,b,c,d = inp
p [b*d,a*c,a*d,b*c].max

Measured memory_bytes: 14508
mod = pow(10, 9) + 7
def powmod(x, y):
    res = 1
    for i in range(y):
        res = res * x % mod
    return res

n = int(input())
ans = powmod(10, n) - powmod(9, n) - powmod(9, n) + powmod(8, n)
ans %= mod
ans = (ans + mod) % mod
print(ans)


Measured memory_bytes: 9100
// finish date: 2019/2/23

#include <bits/stdc++.h>

using namespace std;

#define FOR(i, a, b) for(int (i)=a;(i)<(b);(i)++)
#define rep(i, n)  FOR(i,0,n)
typedef long long ll;
typedef vector<int> vi;
typedef vector<vector<int>> vvi;
typedef vector<vector<vector<int>>>
        vvvi;
typedef vector<ll> vl;
typedef vector<vector<ll>> vvl;
typedef vector<double> vd;
typedef vector<vector<double>> vvd;
typedef vector<vector<vector<double>>> vvvd;
typedef vector<bool> vb;
typedef vector<vector<bool>> vvb;
typedef vector<string> vs;
typedef vector<char> vc;
typedef vector<vector<char>> vvc;
typedef pair<int, int> pii;
typedef pair<ll, int> pli;
typedef pair<ll, pair<int, int>> plii;
const int bigmod = 1000000007;
const int INF = 1050000000;
const long long INFll = 100000000000000000;


int main() {
    int N;
    cin >> N;
    vl a(N);
    rep(i, N) cin >> a[i];
    vl acc(N + 1, 0);
    FOR(i, 1, N + 1) acc[i] = a[i - 1] + acc[i - 1];
    vvl dp(N, vl(N, INFll));
    rep(i, N) dp[i][i] = 0;

    int st, en;
    ll left, right;
    FOR(len, 2, N + 1) {
        rep(i, N) {
            st = i;
            en = i + len - 1;
            if (en >= N) break;
            FOR(j, st, en) {
                left = dp[st][j];
                right = dp[j + 1][en];
                dp[st][en] = min(dp[st][en], left + right + (acc[en+1] - acc[st]));
            }
        }
    }

    cout << dp[0][N - 1] << endl;

    return 0;
}

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

#define pb(n) push_back(n)
#define fi first
#define se second
#define all(r) (r).begin(),(r).end()
#define gsort(st,en) sort((st),(en),greater<int>())
#define vmax(ary) *max_element(all(ary))
#define vmin(ary) *min_element(all(ary))
#define debug(x) cout<<#x<<": "<<x<<endl
#define fcout(n) cout<<fixed<<setprecision((n))
#define scout(n) cout<<setw(n)
#define vary(type,name,size,init) vector< type> name(size,init)

#define rep(i,n) for(int i = 0; i < (int)(n);++i)
#define REP(i,a,b) for(int i = (a);i < (int)(b);++i)
#define repi(it,array) for(auto it = array.begin(),end = array.end(); it != end;++it)
#define repa(n,array) for(auto &n :(array))

using ll = long long;
using vi = vector<int>;
using vl = vector<ll>;
using dict = map<string,int>;
using pii = pair<int,int> ;

constexpr int imax = ((1<<30)-1)*2+1 ;
constexpr int inf = 100000000;
constexpr double PI = acos(-1.0) ;
double eps = 1e-10 ;
const int dy[] = {-1,0,1,0};
const int dx[] = {0,-1,0,1};

inline bool value(int x,int y,int w,int h){
  return (x >= 0 && x < w && y >= 0 && y < h);
}

template<typename T>
void Unique(vector<T> &v){
  sort(all(v));
  v.erase(all(v),v.end());
}

template<typename T>
T ston(string& str, T n){
  istringstream sin(str) ;
  T num ;
  sin >> num ;
  return num ;
}

void Ans(bool f){
  if(f) cout << "YES"<<endl;
  else cout << "NO"<<endl;
}
void Solve(vector<vector<char>> vvc){
  int x = 0,y = 0;
  rep(i,8){
    rep(j,8){
      if(vvc[j][i] == '1'){
        x = j;
        y = i;
        j = 8;
        i = 8;
        break;
      }
    }
  }
  if(x + 1 < 8 && vvc[x+1][y] == '1'){//A,C,E,G
    if(x+2 < 8 && vvc[x+2][y] == '1'){
      cout << 'C'<<endl;
    }
    else if( x-1 >= 0 && y+1 < 8&& vvc[x-1][y+1] == '1'){
      cout << 'G'<<endl;
    }
    else if( y +1 < 8 && vvc[x][y+1] == '1'){
      cout << 'A'<<endl;
    }
    else{
      cout << 'E'<<endl;
    }
  }
  else{//B,D,F
    if(y+2 < 8 && vvc[x][y+2] == '1'){
      cout << 'B'<<endl;
    }
    else if( x+1 < 8 && y + 1 < 8&& vvc[x+1][y+1] == '1'){
      cout << 'F'<<endl;
    }
    else{
      cout << 'D'<<endl;
    }
  }
}
int main(){
  cin.tie(0);
  ios::sync_with_stdio(false);
  while(1){
    vector<vector<char>> v(8,vector<char>(8,0));
    rep(i,8){
      rep(j,8){
        cin>> v[j][i];
      }
    }
    if(cin.eof()){
      break;
    }
    Solve(v);
  }
  return 0;
}

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

static class CodeJam
{
    static long Solve(int N, int[] A)
    {
        int n = 1;
        long cnt = 0;
        foreach (int a in A)
        {
            if (a == n)
            {
                ++n;
            }
            else if (a > n)
            {
                cnt += (a - 1) / n;
                if (n == 1) { n = 2; }
            }
        }
        return cnt;
    }

    static void Main(string[] args)
    {
        int N = int.Parse(Console.ReadLine());
        int[] A = new int[N];
        for (int i = 0; i < N; ++i) { A[i] = int.Parse(Console.ReadLine()); }
        Console.WriteLine(Solve(N, A));
    }
}


Measured memory_bytes: 15328
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AtCoder
{
    class Node<T>
    {
        private int m_height;
        private Node<T> m_parent;
        public T Item { get; private set; }
        public Node(T item)
        {
            m_height = 0;
            m_parent = this;
            Item = item;
        }
        public Node<T> Find()
        {
            if (m_parent == this) { return this; }

            Node<T> parent = m_parent.Find();
            m_parent = parent;
            return parent;
        }
        public static void Unite(Node<T> a, Node<T> b)
        {
            Node<T> p = a.Find();
            Node<T> q = b.Find();
            if (p.m_height < q.m_height)
            {
                p.m_parent = q;
                q.m_height = Math.Max(p.m_height + 1, q.m_height);
            }
            else
            {
                q.m_parent = p;
                p.m_height = Math.Max(q.m_height + 1, p.m_height);
            }
        }
    }
    class Program
    {
        private const int MODULO = 1000000007;
        private static string Read() { return Console.ReadLine(); }
        private static int ReadInt() { return int.Parse(Read()); }
        private static long ReadLong() { return long.Parse(Read()); }
        private static double ReadDouble() { return double.Parse(Read()); }
        private static int[] ReadInts() { return Array.ConvertAll(Read().Split(), int.Parse); }
        private static long[] ReadLongs() { return Array.ConvertAll(Read().Split(), long.Parse); }
        private static double[] ReadDoubles() { return Array.ConvertAll(Read().Split(), double.Parse); }

        static int Solve(int N, int[] P, Tuple<int, int>[] tuples)
        {
            var nodes = new Node<int>[N];
            for (int i = 0; i < N; ++i) { nodes[i] = new Node<int>(i); }
            foreach (var tuple in tuples)
            {
                int a = tuple.Item1;
                int b = tuple.Item2;
                Node<int>.Unite(nodes[a], nodes[b]);
            }
            int count = 0;
            for (int i = 0; i < N; ++i)
            {
                if (nodes[i].Find().Item == nodes[P[i]].Find().Item) { ++count; }
            }
            return count;
        }
        static void Main(string[] args)
        {
            var V1 = ReadInts();
            int N = V1[0];
            int M = V1[1];
            var P = ReadInts().Select(p => p - 1).ToArray();
            var tuples = new Tuple<int, int>[M];
            for (int i = 0; i < M; ++i)
            {
                var V2 = ReadInts();
                tuples[i] = new Tuple<int, int>(V2[0] - 1, V2[1] - 1);
            }
            Console.WriteLine(Solve(N, P, tuples));
        }
    }
}


Measured memory_bytes: 27584
#include <bits/stdc++.h>
#include <iostream>
typedef long long int ll;
using namespace std;
typedef pair<ll,ll> pp;
ll n;string s;

ll M=1000000007;

bool f(pp p1,pp p2)
{
	return p1.second<p2.second;
}


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

    vector<pp> a;
    ll sum=0;
    for(int i=0;i<n;i++)
    {
        ll u,v;
        cin>>u>>v;
        a.push_back(make_pair(u,v));
        sum+=v;
    }
	sort(a.begin(),a.end(),f);
    ll dp[n+1][sum+1];
    ll mx=-1,mxs=-1;
    for(int i=0;i<n;i++)
    {
        for(int j=0;j<=sum;j++)
        {
            if(j==0)
            {
                dp[i][j]=0;
                if(j>=mxs&&dp[i][j]!=-1)
                mxs=j;
                continue;
            }
            if(i==0)
            {
                if(j==a[i].second&&a[i].first<=w)
                dp[i][j]=a[i].first;
                else
                dp[i][j]=-1;
                if(j>=mxs&&dp[i][j]!=-1)
                mxs=j;
                continue;
            }
            else
            {
                if(j-a[i].second>=0&&dp[i-1][j-a[i].second]!=-1&&dp[i-1][j-a[i].second]+a[i].first<=w)
                dp[i][j]=a[i].first+dp[i-1][j-a[i].second];
                else
                dp[i][j]=-1;

                if(dp[i-1][j]!=-1)
                {
                    if(dp[i][j]==-1)
                    dp[i][j]=dp[i-1][j];
                    else
                    {
                        dp[i][j]=min(dp[i][j],dp[i-1][j]);
                    }
                }
                if(j>mxs&&dp[i][j]!=-1)
                mxs=j;
            }
        }
    }
    cout<<mxs<<"\n";
    
 /*   for(int i=0;i<n;i++)
    {
    	for(int j=0;j<=sum;j++)
    	cout<<dp[i][j]<<" ";
    	cout<<"\n";
	}*/

    return 0;
}


Measured memory_bytes: 78336
x, a, b = input().split()
x = int(x)
a = int(a)
b = int(b)
#print("x = ", x)
#print("a = ", a)
#print("b = ", b)

if x < a:
  distance_xa = a - x
else:
  distance_xa = x - a
#print("distance_xa = ", distance_xa)

if x < b:
  distance_xb = b - x
else:
  distance_xb = x - b
#print("distance_xb = ", distance_xb)

if distance_xa < distance_xb:
  print("A")
else:
  print("B")
        

Measured memory_bytes: 3064