akhauriyash/Code-Regression huggingface dataset:
use std::io;


fn main() {
    let mut s = read_one::<String>().chars().collect::<Vec<_>>();
    let mut k = read_one::<usize>();
    let n = s.len();
    for i in 0..n {
        if s[i] == 'a' { continue; }
        let idx = (s[i] as u8 - b'a') as usize;
        // println!("idx: {}", idx);
        if 26 - idx <= k { k -= 26 - idx; s[i] = 'a'; }
    }

    // consume k
    let idx = (s[n - 1] as u8 - b'a') as usize;
    let new = (idx + k) % 26;
    s[n - 1] = (new as u8 + b'a') as char;
    for i in 0..n {
        if i == n - 1 { println!("{}", s[i]); }
        else { print!("{}", s[i]); }
    }
}


#[allow(dead_code)]
fn read<T>() -> Vec<T>
where T:
std::str::FromStr,
T::Err: std::fmt::Debug {

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.split_whitespace()
        .map(|s| s.trim().parse().unwrap())
        .collect()
}

#[allow(dead_code)]
fn read_one<T>() -> T
where T:
std::str::FromStr,
T::Err: std::fmt::Debug {

    let mut buf = String::new();
    io::stdin().read_line(&mut buf).unwrap();
    buf.trim().parse().unwrap()
}

Measured memory_bytes: 4352
//! ----------------------------------------------
//! Framework <https://github.com/vain0x/procon>
//!
//! See the bottom of file for solution.
//! ----------------------------------------------

#![allow(unused_imports)]
#![allow(non_snake_case)]

use std::cell::RefCell;
use std::cmp::{max, min, Ordering};
use std::collections::*;
use std::fmt::{Debug, Display, Formatter, Write as FmtWrite};
use std::io::{stderr, stdin, BufRead, Write};
use std::mem::{replace, swap};
use std::ops::*;
use std::rc::Rc;

/// Print values to standard error if debug mode.
#[allow(unused_macros)]
macro_rules! debug {
    ($($e:expr),*) => {
        #[cfg(debug_assertions)]
        $({
            let (e, mut err) = (stringify!($e), stderr());
            writeln!(err, "\x1B[33m{}\x1B[0m = {:?}", e, $e).unwrap()
        })*
    };
}

/// Read from standard input and parse each word.
/// - `read!(T, U, ..)` parses a line as a tuple of words.
/// - `read![[T]]` parses a line as an array of words.
/// - `read![..; N]` parses `N` lines, using `read!(..)` repeatedly.
#[allow(unused_macros)]
macro_rules! read {
    ([$t:ty] ; $n:expr) =>
        ((0..$n).map(|_| read!([$t])).collect::<Vec<_>>());
    ($($t:ty),+ ; $n:expr) =>
        ((0..$n).map(|_| read!($($t),+)).collect::<Vec<_>>());
    ([$t:ty]) =>
        (rl().split_whitespace().map(|w| w.parse().unwrap()).collect::<Vec<$t>>());
    ($($t:ty),*) => {{
        let buf = rl();
        let mut w = buf.split_whitespace();
        ($(w.next().unwrap().parse::<$t>().unwrap()),*)
    }};
}

/// Read a line from standard input.
#[allow(dead_code)]
fn rl() -> String {
    let mut buf = String::new();
    stdin().read_line(&mut buf).unwrap();

    #[allow(deprecated)]
    buf.trim_right().to_owned()
}

// -----------------------------------------------
// Solution
// -----------------------------------------------

const INF: usize = 1 << 60;

fn char_to_index(c: char) -> usize {
    (c as u8 - b'a') as usize
}

fn main() {
    let s = rl().chars().collect::<Vec<_>>();
    let t = rl();

    let sn = s.len();

    let mut skip = vec![vec![INF; 26]; sn];
    let mut last = vec![INF; 26];

    let mut ai = sn * 2;
    for _ in 0..2 {
        for i in (0..sn).rev() {
            ai -= 1;

            let ci = char_to_index(s[i]);
            last[ci] = ai;

            for ci in 0..26 {
                skip[i][ci] = last[ci];
            }
        }
    }

    let mut i = 0_usize;
    let mut ok = true;

    for c in t.chars() {
        let ci = char_to_index(c);
        let k = skip[i % sn][ci];
        if k == INF {
            ok = false;
            break;
        }

        i += k - (i % sn) + 1;
    }

    if ok {
        println!("{}", i);
    } else {
        println!("-1");
    }
}


Measured memory_bytes: 30972
//Articulation Point
#include <iostream>
#include <vector>
#include <set>

using namespace std;

static const int MAX = 100000;
static const int NIL = -1;

int timer;
int prenum[MAX], parent[MAX], lowest[MAX];
bool visited[MAX];

void dfs(int current, int prev, int n, vector<vector<int>> &G) {
    visited[current] = true;
    prenum[current] = lowest[current] = timer++;

    for(auto next: G[current]) {
        if(!visited[next]) {
            parent[next] = current;
            dfs(next, current, n, G);
            lowest[current] = min(lowest[current], lowest[next]);
        }
        else if(next != prev) {
            lowest[current] = min(lowest[current], prenum[next]);
        }
    }
}

set<int> articulationPoint(int n, vector<vector<int>> &G) {
    parent[0] = NIL;
    for(int i=0; i<n; i++) visited[i] = false;

    timer = 0;
    dfs(0, NIL, n, G);

    set<int> st;
    int np = 0;
    for(int i=1; i<n; i++) {
        int p = parent[i];
        if(p == 0) np++;
        else if(prenum[p] <= lowest[i]) st.insert(p);
    }
    if(np > 1) st.insert(0);
    return st;
}

int main() {
    int n, m, s, t;
    cin >> n >> m;
    vector<vector<int>> G(n);
    for (int i=0; i<m; i++) {
        cin >> s >> t;
        G[s].push_back(t);
        G[t].push_back(s);
    }

    set<int> st = articulationPoint(n, G);

    for(auto a : st) cout << a << endl;

    return 0;
}



Measured memory_bytes: 4564
#include <iostream>
#include <string>
using namespace std;
int main()
{
    string s;
    cin >> s;
    int h, t;
    h = stoi(s.substr(0, 2));
    t = stoi(s.substr(2, 2));
    if (h < 13 && t < 13)
    {
        if (h != 0 && t != 0)
            cout << "AMBIGUOUS";
        else if (h == 0 && t!=0)
            cout << "YYMM";
        else if (t == 0 && h!=0)
            cout << "MMYY";
        else
            cout << "NA";
    }
    else if (h < 13 && t >= 13 && h != 0)
    {
        cout << "MMYY";
    }
    else if (h >= 13 && t < 13 && t != 0)
    {
        cout << "YYMM";
    }
    else
    {
        cout << "NA";
    }
}

Measured memory_bytes: 256
#include<stdio.h>
#define MAX 100000
int n,k;
double T[MAX];
int check(double p){
  int i = 0;
  int j;
  double s;
  for(j = 0; j<k; j++){
    s = 0.0;
    while(s+T[i] <= p){
      s += T[i];
      i++;
      if(i == n)return n;
    }
  }
  return i;
}

int solve(){
  double left = 0.0;
  double right = 100000*10000;
  double mid;
  int v;

  while(right - left > 1){
    mid = (left +right ) /2;
    v = check(mid);
    if(v>= n){
      right = mid;
    }
    else {
      left = mid;
    }
  }
    return right;
  }

  int main(){
    int i;
    double ans;
    scanf("%d%d",&n,&k);
    for(i = 0 ;i < n; i++){
      scanf("%lf", &T[i]);
    }
    ans = solve();
    printf("%d\n",(int)ans);
    return 0;
  }



Measured memory_bytes: 2552
#![allow(unused_imports)]
#![allow(dead_code)]
use std::io::prelude::*;
use std::cmp::{max, min};
use std::collections::{BinaryHeap, HashSet};

const MOD: i64 = 1e9 as i64 + 7;

fn main(){
    let n = read();
    let k = read();
    let mut p: Vec<f64> = (0..n).map(|_| read()).collect();
    for i in &mut p{
        *i = (1.0 + *i) / 2.0;
    }
    let mut sum = 0.0;
    for i in 0..k{
        sum += p[i];
    }
    let mut ans = sum;
    for i in k..n{
        sum += p[i] - p[i - k];
        ans = if ans < sum {sum} else {ans};
    }
    println!("{:.10}", ans);
}

fn read<T>() -> T
where
    T: std::str::FromStr,
{
    let stdin = std::io::stdin();
    let token: String = stdin
        .lock()
        .bytes()
        .map(|c| c.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 <vector>
#include <iostream>
using namespace std;
int main() {
	vector<int> d(4);
	cin >> d[0] >> d[1] >> d[2] >> d[3];
	vector<int> v = { 1, 9, 7, 4 };
	bool ok = true;
	for (int i = 0; i < 4; ++i) {
		if (find(d.begin(), d.end(), v[i]) == d.end()) {
			ok = false;
		}
	}
	cout << (ok ? "YES" : "NO") << endl;
	return 0;
}

Measured memory_bytes: 888
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rep1(i, n) for(int i = 1; i < n+1; i++)
#define sort(A) sort(A.begin(),A.end())
#define reverse(A) reverse(A.begin(),A.end())
#define vecmin(A) *min_element(A.begin(),A.end())
#define vecmax(A) *max_element(A.begin(),A.end())
typedef long long ll;

int main(){
  string s;
  cin >> s;
  int n = s.size();
  string ans = "";
  rep(i,n){
    char c = s[i];
    if(c == '0') ans.push_back('0');
    if(c == '1') ans.push_back('1');
    if(c == 'B') if(ans.size() > 0) ans.erase(ans.size()-1);
  }
  cout << ans << endl;
}

Measured memory_bytes: 256
p $<.to_a.drop(1).map{|x|
	Complex(*x.split.map(&:to_i))
}.product([*0...5000]).select{|x|
	(x[0]/Complex.polar(1,2*Math::PI*x[1]/5000)).arg.abs<Math::PI/2
}.group_by(&:last).map{|x|
	x[1].map(&:first).inject(:+).abs
}.max


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

struct Dinic{
    struct edge { int64_t to, cap, rev;};

    int N, S, T;
    int64_t flow = 0;
    const int64_t INF = 1e18;
    vector<int> level, iter;
    vector<vector<edge>> G;

    Dinic(int N, int S, int T):N(N), S(S), T(T){
        flow = 0;
        level.resize(N);
        iter.resize(N);
        G.resize(N);
    }

    void add_edge(int from, int to, int64_t cap){
        G[from].push_back((edge){to, cap, G[to].size()});
        G[to].push_back((edge){from, 0, G[from].size()-1});
    }

    void bfs(int s){
        fill(level.begin(), level.end(), -1);
        queue<int> que;
        level[s] = 0;
        que.push(s);
        while(que.size()){
            int v = que.front(); que.pop();
            for(auto& e : G[v]){
                if(e.cap > 0 && level[e.to] < 0){
                    level[e.to] = level[v] + 1;
                    que.push(e.to);
                }
            }
        }
    }

    int64_t dfs(int v, int t, int64_t f){
        if(v == t) return f;
        for(int i=iter[v]; i<G[v].size(); i++){
            auto& e = G[v][i];
            if(e.cap > 0 && level[v] < level[e.to]){
                int64_t d = dfs(e.to, t, min(f, e.cap));
                if(d > 0){
                    e.cap -= d;
                    G[e.to][e.rev].cap += d;
                    return d;
                }
            }
        }
        return 0;
    }

    int64_t max_flow(){
        while(true){
            bfs(S);
            if(level[T] < 0) return flow;
            fill(iter.begin(), iter.end(), 0);
            while(true){
                int64_t f = dfs(S, T, INF);
                if(f == 0) break;
                flow += f;
            }
        }
    }
};

int main(){
    int N, V[20], C[20];
    cin >> N;
    for(int i=0; i<N; i++) cin >> V[i];
    for(int i=0; i<N; i++) cin >> C[i];

    int S = N, T = N+1;
    Dinic dinic(T+1, S, T);
    for(int i=0; i<N; i++){
        dinic.add_edge(S, i, C[i]);
        dinic.add_edge(i, T, V[i]);
    }

    int ans = 0;
    for(int i=0; i<N; i++) ans += V[i];
    ans -= dinic.max_flow();
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
import sys
input = sys.stdin.readline


def main():
    K, T = map(int, input().split())
    A = list(map(int, input().split()))
    cakes = []
    for i, a in enumerate(A):
        cakes.append([i, a])

    order = [-1]*K
    pre = -1
    for j in range(K):
        uniq = False
        cakes.sort(key=lambda x: x[1], reverse=True)
        for i in range(T):
            if cakes[i][0] != pre and cakes[i][1] > 0:
                pre = order[j] = cakes[i][0]
                cakes[i][1] -= 1
                uniq = True
                break
        if not uniq:
            pre = order[j] = cakes[0][0]

    pre = -1
    tmp = 0
    ans = 0
#    print(order)
    for i in order:
        if i == pre:
            tmp += 1
            ans = max(ans, tmp)
        else:
            pre = i
            tmp = 0
    print(ans)


if __name__ == '__main__':
    main()


Measured memory_bytes: 3064
#include <iostream>
#include <string>
#include <stdio.h>

using namespace std;

int main(){
  	string str;
  	cin >> str;
	size_t a = str.length()%2;
  	size_t n = str.length()/2;
  
	if (a > 0){
        cout << "No" <<endl;
        return 0;
    }
  
	int count = 0;
  	for (int i = 0; i < str.size(); i++) {
    	if (str.at(i) == 'h' && str.at(i+1) == 'i') {
      	count++;
    	}
    }  
  
    if (count == n){
        cout << "Yes" <<endl;
        return 0;
    }

    cout << "No" <<endl;
    return 0;
}

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

int main(){

    int a,b,c,d,l,r;
    cin >> a >> b >> c >> d;

    l = a+b;
    r = c+d;

    if(l>r){
        cout << "Left" << endl;
    }else if(l==r){
        cout << "Balanced" << endl;
    }else if(l<r){
        cout << "Right" << endl;
    }

}


Measured memory_bytes: 256
#include<cstdio>
#include<cstring>
#include<algorithm>
#define N 16
using namespace std;
const int mod = 1e9+7;
inline int read(){
	int sum = 0, t = 1; char ch = getchar();
	while(ch < '0' || ch > '9'){ if(ch == '-') t = -1; ch = getchar(); }
	while(ch >= '0' && ch <= '9'){ sum = sum * 10 + ch - '0'; ch = getchar(); }
	return sum * t;
}

int n, m, G[N];
int cnt[1<<N];
int f[1<<N];

void upd(int &x, int y){ x += y; if(x >= mod) x -= mod; }

int main(){
	n = read(); m = read();
	for(int S = 1; S < 1 << n; S++) cnt[S] = cnt[S ^ (S & -S)] + 1;
	for(int i = 1; i <= m; i++){
		int x = read() - 1, y = read() - 1;
		G[x] |= 1 << y;
	}
	f[0] = 1;
	for(int S = 0; S < 1 << N; S++) if((S >> 1 & 1) == (S & 1))
		for(int T = S; T ; T = T - 1 & S) if((T >> 1 & 1) == (T & 1)){
			int tmp = 1;
			for(int i = 0; i < n; i++) if(S >> i & 1){
				if(T >> i & 1) tmp = 1LL * tmp * (1 << cnt[G[i] & (S ^ T)]) % mod;
				else tmp = 1LL * tmp * ((1 << cnt[G[i] & T]) - 1) % mod;
			}
			upd(f[S], 1LL * f[S ^ T] * tmp % mod);
		}
	int pw = 1;
	for(int i = 1; i <= m; i++) pw = 1LL * pw * 2 % mod;
	printf("%d\n", (pw - f[(1 << n) - 1] + mod) % mod);
}



Measured memory_bytes: 640
#include<cstdio>
#define N 100005
using namespace std;
int max(int a,int b){
	return a>b?a:b;
}
char s[N];
int cnt,n;
int getnext(char qw){
	for(int i=0;;++i){
		if(s[cnt+i]!=qw){
			cnt+=i;
			return i;
		}
		if(cnt+i==n){
			cnt+=i;
			return i;
		}
	}
}
int solve[N];
int main(){
	int k;
	scanf("%d%d%s",&n,&k,s);
	int count=0;
	for(;cnt!=n;++count){
		solve[count]=getnext('1');
		++count;
		solve[count]=getnext('0');
	}
	int ans=0,tmp=solve[0];
	for(int i=1;i<count;i+=2){
		tmp+=solve[i]+solve[i+1];
		if((i>>1)>=k){
			tmp-=solve[i-(k<<1)-1]+solve[i-(k<<1)];
		}
		ans=max(ans,tmp);
	}
	printf("%d",ans);
}

Measured memory_bytes: 640
#include <bits/stdc++.h>
#define rep(i,n) for(ll i=0;i<(n);++i)
#define all(a) (a).begin(),(a).end()
#define dunk(a) cout << (a) << endl
#define rall(a) (a).rbegin(),(a).rend()
const int INF = 2e9;
using namespace std;
using Graph = vector<vector<int>>;
typedef pair<int,int> P;
typedef long long ll;

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

ll lcm(ll a, ll b) {return a / gcd(a, b) * b;}

int main(){
    int n; cin >> n;
    ll ans = 1ll;

    rep(i,n){
        ll t; cin >> t;
        ans = lcm(ans,t);
    }

    cout << ans << endl;
}



Measured memory_bytes: 256
N, A, B = map(int, input().split())

if A + B - 1 > N or A * B < N:
    print(-1)
    quit()

ans = []

x = N - A
cur = 1
while cur <= N:
    y = min(x + 1, B)
    ans += list(reversed(range(cur, cur + y)))
    cur += y
    x -= y - 1

print(*ans)

Measured memory_bytes: 21856
K,S=map(int,input().split())
count=0
for X in range(K,-1,-1):
  if S-X>2*K:
    break    
  for Y in range(K,-1,-1):
    if 0<=S-(X+Y)<=K:
       count+=1
    elif 0>S-(X+Y):
       continue
    else:    
       break
print(count)

Measured memory_bytes: 3060
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;

public class Main {
    int n;
    int[] as, bs, cs;

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

    void run() {
        FastReader sc = new FastReader();
        n = sc.nextInt();
        as = new int[n];
        bs = new int[n];
        cs = new int[n];
        for (int i = 0; i < n; i++) {
            as[i] = sc.nextInt();
        }
        for (int i = 0; i < n; i++) {
            bs[i] = sc.nextInt();
        }
        for (int i = 0; i < n; i++) {
            cs[i] = sc.nextInt();
        }
        solve();
    }

    void solve() {
        Arrays.sort(as);
        Arrays.sort(bs);
        Arrays.sort(cs);
        int[] cBoundsForB = new int[n];
        for (int i = 0; i < n; i++) {
            cBoundsForB[i] = lower_bound(cs, bs[i] + 1);
        }
        long[] possibilitiesForB = new long[n];
        if (cBoundsForB[n - 1] < n) {
            possibilitiesForB[n - 1] = n - cBoundsForB[n - 1];
        }
        for (int i = n - 2; i >= 0; i--) {
            possibilitiesForB[i] = n - cBoundsForB[i] + possibilitiesForB[i + 1];
        }
        long ans = 0;
        for (int i = 0; i < n; i++) {
            int bBound = lower_bound(bs, as[i] + 1);
            if (bBound < n) {
                ans += possibilitiesForB[bBound];
            }
        }
        System.out.println(ans);
    }

    static int lower_bound(int[] arr, int key) {
        int low = 0;
        int high = arr.length - 1;
        while (high - low >= 0) {
            int mid = (low + high) / 2;
            if (key <= arr[mid]) {
                high = mid - 1;
            } else {
                low = mid + 1;
            }
        }
        return low;
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new
                    InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }

        long nextLong()
        {
            return Long.parseLong(next());
        }

        double nextDouble()
        {
            return Double.parseDouble(next());
        }

        String nextLine() {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
}


Measured memory_bytes: 53760
#include<bits/stdc++.h>
using namespace std;
int main(){
	int a,b,c;
	cin>>a>>b>>c;
	if((a==b&&b!=c)||(a==c&&a!=b)||(b==c&&c!=a)){
		cout<<"Yes";
	}
	else{
		cout<<"No";
	}
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define rep(i, a, b) for(register int i = a; i <= b; i++)
#define per(i, a, b) for(register int i = a; i >= b; i--)
typedef long long LL;
const LL mod = 998244353;
const int N = 3e5 + 5;

int n;
LL a, b, k, ans, fac[N], inv[N];

LL Ksm(LL a, LL b) {
	LL res = 1;
	while(b) {
		if(b&1) res = res*a%mod;
		b /= 2;
		a = a*a%mod;
	}
	return res;
}

LL cal(int n, int k) {
	return fac[n]*inv[k]%mod*inv[n - k]%mod;
}

int main() {
	cin>>n>>a>>b>>k;
	fac[0] = inv[0] = 1;
	rep(i, 1, n) fac[i] = fac[i - 1]*i%mod, inv[i] = Ksm(fac[i], mod - 2);
	rep(i, 0, n) {
		if(a*i > k) break;
		if((k - a*i)%b) continue;
		if((k - a*i)/b > n) continue;
		int t = (k - a*i)/b;
		ans = (ans + cal(n, t)*cal(n, i)%mod)%mod;
	}
	cout<<ans<<endl;
}

Measured memory_bytes: 8292
import numpy as np
N, M = list(map(int, input().split(" ")))
dp = [np.inf] * (1 << N)
dp[0] = 0
bits = set()
bits.add(0)

for i in range(M):
    val,b = list(map(int, input().split(" ")))
    opens = list(map(int, input().split(" ")))
        
    # OpensからBitへの変換
    keybits = 0
    for tmp in opens:
        keybits += 1 << tmp-1
    
    for prev in list(bits):
        target = prev | keybits
        dp[target] = min(dp[target], dp[prev]+val)
        bits.add(target)
    
print(dp[-1] if dp[-1] != np.inf else -1)

Measured memory_bytes: 14632
import java.util.Scanner;

public class Main {

	public static void main (String[] args) {

		Scanner sc = new Scanner(System.in);

		String a = sc.nextLine();

		int sum = 0;

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

			if (a.charAt(i) == '+') {
				sum++;
			} else {
				sum--;
			}
		}

		System.out.println(sum);

	}
}


Measured memory_bytes: 23508
//#include <ext/pb_ds/assoc_container.hpp> 
//#include <ext/pb_ds/tree_policy.hpp>
//#include <bits/stdc++.h>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <vector>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <valarray>
#include <iterator>
#include <functional>
#include <limits>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <cassert>
#include <unordered_map>
#include <unordered_set>
#include <stack>
using namespace std;
#define IOS ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define trace(x) cerr << #x << ": " << x << " " << endl;
 
typedef int64_t ll;
 
#define endl '\n'
#define int ll
ll mod=1e9+7;
ll mod1=1e9+5;
ll power(ll a,ll b)
{
    if(b==0) return 1;
    else if(b%2==0)
        return power(((((a)%mod)*((a)%mod))%mod),b/2)%mod;
    else return (((a)%mod)*(power(((((a)%mod)*((a)%mod))%mod),b/2)%mod))%mod;
}
inline ll inverse(ll a,ll md) {
  a %= md;
  if (a < 0) a += md;
  ll b = md, u = 0, v = 1;
  while (a) {
    ll t = b / a;
    b -= t * a; swap(a, b);
    u -= t * v; swap(u, v);
  }
  assert(b == 1);
  if (u < 0) u += md;
  return u;
}
  
  
 //using namespace __gnu_pbds;
 //#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
//find_by_order(k)  returns iterator to kth element starting from 0;
//order_of_key(k) returns count of elements strictly smaller than k;
//erase,insert same as normal set
//mt19937 mrand(chrono::high_resolution_clock::now().time_since_epoch().count()); //for randomized solution
const int ce=1e9+7;
ll fast_mod(ll input)
{
    return input < ce ? input : input%ce;
}

int32_t main()
{
    IOS
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    #endif    
    
    int h,w;
    cin>>h>>w;
    int m;
    cin>>m;
    pair<int,int> a[h+1];
    for(int i=1;i<=h;i++)
    {
        a[i].first=0;
        a[i].second=i;
    }
    pair<int,int> b[w+1];
    for(int i=1;i<=w;i++)
    {
        b[i].first=0;
        b[i].second=i;
    }

    map<pair<int,int>,int> m1;
    while(m--)
    {
        int x,y;
        cin>>x>>y;
        m1[{x,y}]++;
        a[x].first++;
        b[y].first++;
    }
    sort(a+1,a+h+1,greater<pair<int,int>>());
    sort(b+1,b+w+1,greater<pair<int,int>>());
    int ans=a[1].first+b[1].first-m1[{a[1].second,b[1].second}];
    if(m1[{a[1].second,b[1].second}]==0)
    {
        cout<<ans;
        return 0;
    }
    int te=ans;
    for(int i=1;i<=h;i++)
    {
        if(a[i].first!=a[1].first)
            break;
        if(te>ans)
            break;
        for(int j=1;j<=w;j++)
        {
            if(b[j].first!=b[1].first)
                break;
            if(m1[{a[i].second,b[j].second}]==0)
            {
                //cout<<a[i].second<<" "<<b[j].second<<endl;
                te=ans+1;
                break;
            }
        }
    }
    cout<<te;
    
}    
 

Measured memory_bytes: 31788
#include<cstdio>
#include<algorithm>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PA;
const int N=200005,p=1000000007;
PA T[N],Z[N],FZ[N];
int ni[N],C[N],t[N],A[N],H[N],i,j,k,n,m,an,R;
char c;

inline char getc()
{
	#define VV 10000000
	static char s[VV],*l=s,*r=s;
	if (l==r)
		l=s,r=s+fread(s,1,VV,stdin);
	return l==r?0:*l++;
}

int read(){ int z=0; do c=getc(); while (c<'0'||c>'9'); while (c>='0'&&c<='9') z*=10,z+=c-'0',c=getc(); return z; }

void Plus(int &a,int b){ a+=b,a-=a<p?0:p; }
void Minus(int &a,int b){ a-=b,a+=a<0?p:0; }

PA operator *(const PA &A,const int &b)
{
	return b?PA((LL)A.fi*b%p,A.se):PA(A.fi,A.se+1);
}

void operator +=(PA &A,const PA &B)
{
	if (A.se<B.se)
		A=B;
	else
		if (A.se==B.se)
			Plus(A.fi,B.fi);
}

int power(int z,int k)
{
	int d=1;
	for (;k;z=(LL)z*z%p,k>>=1) if (k&1) d=(LL)d*z%p;
}

PA mt(int w,PA z)
{
	for (;w<=n;w+=w&-w) T[w]+=z;
}

PA qt(int w)
{
	PA z=PA(0,0);
	for (;w;w-=w&-w) z+=T[w];
	return z;
}

void add(int w){ for (;w<=n;w+=w&-w) ++t[w]; }
int getsum(int w){ int z=0; for (;w;w-=w&-w) z+=t[w]; return z; }

int solve()
{
	ni[2]=p+1>>1;
	n=read(),R=1;
	for (i=1;i<=n;++i) ++C[A[i]=read()];
	for (i=n;i;--i)
	{
		C[i]+=C[i+1],H[i]=C[i]-(n-i);
		if (H[i]<=0) return 0;
		R=(LL)R*H[i]%p;
	}
	for (ni[1]=1,i=2;i<=n;++i) ni[i]=p-(LL)(p/i)*ni[p%i]%p;
	ni[0]=0;
	Z[0]=FZ[0]=PA(1,0);
	for (i=1;i<=n;++i)
		Z[i]=Z[i-1]*((LL)(H[i]-1)*ni[H[i]]%p),
		FZ[i]=FZ[i-1]*((LL)H[i]*ni[H[i]-1]%p);
	
	for (i=1;i<=n;++i)
	{
		int d=A[i];
		PA D=qt(d);
		if (D.se==Z[d].se)
			Plus(an,(LL)D.fi*Z[d].fi%p);
		mt(d,FZ[d]);
	}
	for (i=1;i<=n;++i) T[i]=PA(0,0);
	for (i=n;i;--i)
	{
		int d=A[i];
		PA D=qt(d-1);
		if (D.se==Z[d].se)
			Minus(an,(LL)D.fi*Z[d].fi%p);
		mt(d,FZ[d]);
		Plus(an,(getsum(d-1)<<1)%p),
		add(d);
	}
	
	return (LL)an*R%p*ni[2]%p;
}

int main()
{
	printf("%d\n",solve());
	return 0;
}

Measured memory_bytes: 10368
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<ll,ll> P;
typedef pair<int,int> Pi;
#define rep(i,n) for(ll i=0;i<n;i++)
#define FOR(i,a,b) for(ll i=a;i<b;i++)
#define fi first
#define se second

template<typename T> inline bool chmax(T &a, T b){if(a<b){a=b;return true;}return false;}
template<typename T> inline bool chmin(T &a, T b){if(a>b){a=b;return true;}return false;}
template<typename T> ostream& operator<<(ostream& s,const complex<T>& d) {return s<<"("<<d.real()<<", "<<d.imag()<< ")";}
template<typename T1, typename T2> ostream& operator<<(ostream& s,const pair<T1,T2>& d) {return s<<"("<<d.first<<", "<<d.second<<")";}
template<typename T> ostream& operator<<(ostream& s, const vector<T>& d){int len=d.size();rep(i,len){s<<d[i];if(i<len-1) s<<" ";}return s;}
template<typename T> ostream& operator<<(ostream& s,const vector<vector<T>>& d){int len=d.size();rep(i,len){s<<d[i]<<endl;}return s;}
template<typename T> ostream& operator<<(ostream& s,const set<T>& v){s<<"{ ";for(auto itr=v.begin();itr!=v.end();++itr) {if (itr!=v.begin()) {s<< ", ";}s<<(*itr);}s<<" }";return s;}
template<typename T1, typename T2> ostream& operator<<(ostream& s,const map<T1,T2>& m){s<<"{"<<endl;for(auto itr=m.begin();itr!=m.end();++itr){s<<" "<<(*itr).first<<" : "<<(*itr).second<<endl;}s<<"}"<<endl;return s;}

const ll mod=1e9+7;
const ll inf=1e17;
const int INF=1e9;
const double PI=acos(-1);
const double EPS=1e-10;

int main(){
	cin.tie(0);ios::sync_with_stdio(false);
	int n,u,v;
	cin>>n>>u>>v;
	u--,v--;
	vector<vector<int>> g(n);
	rep(i,n-1){
		int a,b;
		cin>>a>>b;
		a--,b--;
		g[a].push_back(b);
		g[b].push_back(a);
	}
	if(u==v){
		cout<<0<<endl;
		return 0;
	}
	vector<vector<int>> dist(2,vector<int>(n,INF));
	auto dfs=[&](auto &dfs,int v,int pre,int flag,int now)->void{
		dist[flag][v]=now;
		for(auto itr:g[v]){
			if(itr==pre) continue;
			dfs(dfs,itr,v,flag,now+1);
		}
	};
	dfs(dfs,u,-1,0,0);
	dfs(dfs,v,-1,1,0);
	int ans=0;
	rep(i,n){
		if(g[i].size()==1){
			if(dist[0][i]<dist[1][i]){
				chmax(ans,dist[1][i]-1);
			}
		}
	}
	cout<<ans<<endl;
}

Measured memory_bytes: 9080
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
vector<int>es[100];
int max_length;
bool used[100];
void get_max_length(int at_pos,int sum_length){
    used[at_pos]=true;
    for(int i=0;i<es[at_pos].size();i++){
        int next_pos=es[at_pos][i];
        if(used[next_pos])continue;
        get_max_length(next_pos,sum_length+1);
    }
    max_length=max(max_length,sum_length);
    used[at_pos]=false;
}
int main(){
    int n;
    while(scanf("%d",&n),n){
        for(int i=0;i<100;i++)es[i].clear();
        max_length=0;
        for(int i=0;i<n;i++){
            int a,b;
            scanf("%d%d",&a,&b);
            a--;b--;
            es[a].push_back(b);
            es[b].push_back(a);
        }
        for(int i=0;i<100;i++)
            get_max_length(i,1);

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

Measured memory_bytes: 1056
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
using namespace std;
#define REP(i,m,n) for(int i=(int)m ; i < (int) n ; ++i )
#define rep(i,n) REP(i,0,n)
typedef long long ll;
typedef pair<int,int> pint;
typedef pair<ll,int> pli;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1e9+7 ;
    using namespace std;
 
    int main(){
      int count=0;
      string s;
      int k;
      cin >> s >> k;
      string t;
      t+=s;
      string x[100000];
      int c=0;
      sort(t.begin(),t.end());
        rep(i,s.size()){
          rep(k,5){
            
         if(s[i]==t[k]){
           rep(j,5-k){
            if(i+j<=s.size()-1)x[c]+=s[i+j]; 
           }
           c++;
         }
          }
        }
      sort(x,x+c);
      int d=0;
      string p[100000];
      rep(i,c){
       rep(j,x[i].size()){
         p[d]+=x[i].substr(0,j+1);
         d++;
       }
      }
      sort(p,p+d);
      rep(i,d){
       if(p[i+1]!=p[i])count++;
        if(count==k){
          cout << p[i] << endl;
          break;
        }
      }
      return 0;}

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

using namespace std;

int h, w, k;
vector<string> s(11);

int find(vector<int> v) {
	v.push_back(h-1);
	int n = v.size();
	vector<int> prev(n);
	int res = 0;
	for(int i = 0; i < w; i++) {
		int cur = 0;
		for(int j = 0; j < h; j++) {
			if(s[j][i] == '1') prev[cur]++;
			if(j == v[cur]) cur++;
		}
		bool flag = false;
		for(int j = 0; j < n; j++) {
			if(prev[j] > k){
				flag = true;
			} 
		}
		if(flag) {
			res++;
			fill(prev.begin(), prev.end(), 0);
			cur = 0;
			for(int j = 0; j < h; j++) {
				if(s[j][i] == '1') prev[cur]++;
				if(prev[cur] > k) return 1e9;
				if(j == v[cur]) cur++;
				//if(prev[cur] > k) return 1e9;
			}
		}
	}
	for(auto i : v)
	return res;
}

int main() {
	ios_base::sync_with_stdio(0);
	cin.tie(NULL);
	cin >> h >> w >> k;
	for(int i = 0; i < h; i++) {
		cin >> s[i];
	}
	int ans = INT_MAX;
	for(int i = 0; i < (1 << (h-1)); i++) {
		vector<int> v;
		for(int j = 0; j < h-1; j++) {
			if(i & (1 << j)) {
				v.push_back(j);
			}
		}
		ans = min(ans, (int)v.size() + find(v));
	}
	cout << ans << '\n';

	return 0;
}


Measured memory_bytes: 256
#include <cstring>
#include <cstdio>
#define MOD 1000000007
typedef long long ll;
inline ll quick_pow(ll a, ll n)
{
	ll res = 1;
	while (n)
	{
		if (n & 1)
			res = res * a % MOD;
		a = a * a % MOD;
		n >>= 1;
	}
	return res;
}
struct Matrix
{
	ll arr[2][2];
	Matrix()
	{
		memset(arr, 0, sizeof(arr));
	}
	inline ll *operator [](const int &x)
	{
		return arr[x];
	}
	inline const ll *operator [](const int &x) const
	{
		return arr[x];
	}
	inline Matrix operator *(const Matrix &a) const
	{
		Matrix res;
		for (int i = 0; i < 2; i++)
		{
			for (int j = 0; j < 2; j++)
			{
				for (int k = 0; k < 2; k++)
					(res[i][k] += arr[i][j] * a[j][k]) %= MOD;
			}
		}
		return res;
	}
};
char str[1005][1005];
int main()
{
	// freopen("AGC003-F.in", "r", stdin);
	int n, m;
	ll k;
	scanf("%d%d%lld", &n, &m, &k);
	for (int i = 0; i < n; i++)
		scanf("%s", str[i]);
	int lr = 0, ud = 0, blk = 0, adj = 0;
	for (int i = 0; i < n; i++)
		lr += str[i][0] == '#' && str[i][m - 1] == '#';
	for (int i = 0; i < m; i++)
		ud += str[0][i] == '#' && str[n - 1][i] == '#';
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
			blk += str[i][j] == '#';
	}
	if (k == 1 || (lr && ud))
	{
		puts("1");
		return 0;
	}
	ll ans = quick_pow(blk, k - 1);
	if (lr)
	{
		for (int i = 0; i < n; i++)
		{
			for (int j = 1; j < m; j++)
				adj += str[i][j] == '#' && str[i][j - 1] == '#';
		}
	}
	else
	{
		for (int i = 1; i < n; i++)
		{
			for (int j = 0; j < m; j++)
				adj += str[i][j] == '#' && str[i - 1][j] == '#';
		}
	}
	Matrix res, trans;
	res[0][0] = adj;
	res[0][1] = blk;
	trans[0][0] = lr + ud;
	trans[1][0] = adj;
	trans[1][1] = blk;
	k -= 2;
	while (k)
	{
		if (k & 1)
			res = res * trans;
		trans = trans * trans;
		k >>= 1;
	}
	if (!lr && !ud)
		printf("%lld\n", ans);
	else
		printf("%lld\n", (ans - res[0][0] + MOD) % MOD);
	return 0;
}


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

using namespace std;

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

const int INF = 1000000000;
const ll LINF = (ll) 4000000000000000000;
const ll MOD = (ll) 1000000007;
const double PI = acos(1.0);
const int limit = 100010;

#define REP(i,m,n) for(ll i = m; i < (ll)(n); ++i)
#define rep(i,n) REP(i, 0, n)
#define MP make_pair
#define YES(n) cout << ((n) ? "YES" : "NO") << endl
#define Yes(n) cout << ((n) ? "Yes" : "No") << endl
#define Possible(n) cout << ((n) ? "Possible" : "Impossible") << endl
#define NP(v) next_permutation(v.begin(),v.end())
#define smaller_queue  priority_queue <ll, vector<ll>, greater<ll> >
//------------------------------------------------------

ll gcd(ll a, ll b) {
    if (a < b) swap(a, b);
    return b ? gcd(b, a % b) : a;
}

int main() {
    int t;
    cin >> t;

    rep(k, t) {
        ll a, b, c, d;
        cin >> a >> b >> c >> d;
        if (b > d || a < b) Yes(false);
        else {
            ll g = gcd(b, d);
            ll p = c + g - (c - a % g + g) % g;
            Yes(p - b >= 0);
        }
    }


    return 0;
}



Measured memory_bytes: 256
#include<bits/stdc++.h>
#define INT long long int

using namespace std;
INT n, cnt, sum;
int main()
{
    cin>>n;
    while( n >= 10 ) sum += n%10, n/=10, cnt++;
    sum += n;
    if( cnt == 0 ) cout<<n<<endl;
    else cout<<max(sum, cnt*9+(n-1))<<endl;
    return 0;
}



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

using namespace std;
int main(){
  int x,y;
  cin >> x >> y;
  while(x!=0 || y!=0){
    if(x<y) cout << x << " " << y <<endl;
    else cout << y << " " << x << endl;
    cin >> x >> y;
  }
  return 0;
}


Measured memory_bytes: 3020
#include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <stdlib.h>
#include <string.h>
#include <cstring>
#include <cmath>
#include <map>
#include <queue>
#include <deque>
#include <stack>
#include <set>
#include <stdio.h>
#include <tuple>
#include <bitset>
#include <cfloat>
#include <fstream>
#include <limits.h>
#include <list>
#include <math.h>
#include <random>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <numeric>
#include <utility>
#include <sstream>
// *テンプレート*
#define int long long
#define rep(i, n) for (int i = 0; i < (n); i++)
#define P pair<int, int>
// aよりbの方が小さかったら、aの値をbの値に置き換える。(swapではない！)
template<class T> inline bool chmin(T& a, T b) {
	if (a > b) {
		a = b;
		return true;
	}
	return false;
}
// aよりbの方が大きかったら、aの値をbの値に置き換える。
template<class T> inline bool chmax(T& a, T b) {
	if (a < b) {
		a = b;
		return true;
	}
	return false;
}

using namespace std;
typedef long long ll;
using Graph = vector<vector<int>>;
//最大公約数
ll gcd(ll a, ll b) {
	if (a < b)swap(a, b);
	if (b == 0) return a;
	return gcd(b, a % b);
}
//最小公倍数
ll lcm(ll a, ll b) {
	ll g = gcd(a, b);
	return a / g * b;
}
// 素数かどうか判定
bool prime(int n) {
	for (int i = 2; i <= sqrt(n); i++) {
		if (n%i == 0)return false;
	}
	return n != 1;
}

const long long MOD = 1000000007;
const long long INF = 1LL << 60;
// *テンプレートここまで*

// pair -> vector<pair<int,int>> 
//		   AandB.push_back(make_pair(a[i],b[i]))


signed main() {
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	string s; cin >> s;
	int ans = 1;
	char now = s[0];
	for (int i = 1; i < s.size(); i++) {
		if (s[i] == now) {
			i++; now = '*';
			if (i >= s.size())break;
		}
		else {
			now = s[i];
		}
		ans++;
	}
	cout << ans << endl;
	return 0;
}

Measured memory_bytes: 720
#include<bits/stdc++.h>
using namespace std;
int N,M,i,j,A[9],num[9]={2,5,5,4,5,6,3,7,6};
string dp[10101];
void chmax(string &s,string t){
  if(s=="_"||s.size()<t.size()||(s.size()==t.size()&&s<t))s=t;
}
int main(void){
  cin>>N>>M;
  for(i=0;i<M;i++)cin>>A[i];
  fill(dp,dp+10101,"_");
  dp[0]="";
  for(i=0;i<=N;i++){
    if(dp[i]=="_")continue;
    for(j=0;j<M;j++)chmax(dp[i+num[A[j]-1]],dp[i]+to_string(A[j]));
  }
  cout<<dp[N]<<endl;
  return EXIT_SUCCESS;
}


Measured memory_bytes: 33024
#include <bits/stdc++.h>
using namespace std;
 
int main() {
  int N;
  cin>>N;
  
 int x=1;
   int y=1;
   while(x<=N)
   {x=6*x;}  
   while(y<=N)
   {y=y*9;}
  int s=100001;


 for(int i=0;i<N+1;i=i+1)
  {int r=0;
int a=x;
   int b=y;
  int t=i;
   while(t>0)
   {if(a>5) a=a/6;
    r=r+t/a;
      t=t-(t/a)*a;
   }  
    t=N-i;
   while(t>0)
   {if(b>8) b=b/9;
    r=r+t/b;
      t=t-(t/b)*b;
    } 
   if(s>r) s=r;}
  cout<<s<<endl;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
#define ALL(a) (a).begin(), (a).end()
#define RALL(a) (a).rbegin(), (a).rend()
#define pb push_back
#define FOR(i, a, b) for (int i = (a); i < (b); ++i)
#define rep(i, n) FOR(i, 0, n)
#define ll long long
using namespace std;

const ll P = 1000000007;
const long long INF = 1LL << 60;
int gcd(int a, int b) { return b != 0 ? gcd(b, a % b) : a; }
int lcm(int a, int b) { return a / gcd(a, b) * b; }
vector<char> Alphabet = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
vector<char> alphabet = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }


int main()
{
  cout << fixed << setprecision(10);
  string S;
  cin >> S;
  int N = S.size();
  int sum = 0;
  rep(i,N)
  {
    int a = S[i] - '0';
    sum += a;
  }
  if(sum%9==0)
  {
    cout << "Yes" << endl;
  }
  else cout << "No" << endl;
  return 0;
}


Measured memory_bytes: 3720
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <map>
#include <set>
#include <list>
#include <queue>
#include <deque>
#include <stack>
#include <vector>
#include <algorithm>
#include <functional>
#include <cstring>
#include <string>
#include <sstream>
#include <bitset>
using namespace std;
#define INF	100000000
#define MOD 1000000007
#define pb push_back
#define mp make_pair
#define fi first
#define sec second
#define lb lower_bound
#define ub upper_bound
#define SS stringstream
#define rep(i,n) for(int i = 0; i < n; i++)
#define SORT(x) sort((x).begin(), (x).end())
#define clr(a,b) memset((a),(b),sizeof(a))
typedef long long int ll;
typedef pair<int, int> P;
typedef vector<int> Vi;
typedef vector<ll> Vll;
typedef vector<P> Vp;
typedef priority_queue<P, vector<P>, greater<P> > PQ;

int n, w, d;
int p[100], s[100];

void solve(){
	rep(i,n) scanf("%d%d", &p[i], &s[i]);
	Vp v;
	v.pb(P(w,d));
	rep(i,n){
		vector<P>::iterator ite = v.begin()+p[i]-1;
		P p = *ite;
		ite = v.erase(ite);
		s[i] %= (p.fi*2+p.sec*2);
		if(s[i] < p.fi){
			if(s[i]*p.sec > (p.fi-s[i])*p.sec){
				v.pb(P(p.fi-s[i],p.sec));
				v.pb(P(s[i],p.sec));
			} else{
				v.pb(P(s[i],p.sec));
				v.pb(P(p.fi-s[i],p.sec));
			}
		} else if(s[i] < p.fi+p.sec){
			s[i] -= p.fi;
			if(s[i]*p.fi > (p.sec-s[i])*p.fi){
				v.pb(P(p.fi,p.sec-s[i]));
				v.pb(P(p.fi,s[i]));
			} else{
				v.pb(P(p.fi,s[i]));
				v.pb(P(p.fi,p.sec-s[i]));
			}
		} else if(s[i] < p.fi*2+p.sec){
			s[i] -= p.fi+p.sec;
			if(s[i]*p.sec > (p.fi-s[i])*p.sec){
				v.pb(P(p.fi-s[i],p.sec));
				v.pb(P(s[i],p.sec));
			} else{
				v.pb(P(s[i],p.sec));
				v.pb(P(p.fi-s[i],p.sec));
			}
		} else{
			s[i] -= p.fi*2+p.sec;
			if(s[i]*p.fi > (p.sec-s[i])*p.fi){
				v.pb(P(p.fi,p.sec-s[i]));
				v.pb(P(p.fi,s[i]));
			} else{
				v.pb(P(p.fi,s[i]));
				v.pb(P(p.fi,p.sec-s[i]));
			}
		}
	}
	Vi ans;
	rep(i,n+1) ans.pb(v[i].fi*v[i].sec);
	sort(ans.begin(),ans.end());
	rep(i,n+1){
		if(i != 0) printf(" ");
		printf("%d", ans[i]);
	}
	printf("\n");
}

int main(){
	while(scanf("%d%d%d", &n, &w, &d), n||w||d) solve();
}

Measured memory_bytes: 1216
from collections import deque
import sys
input = sys.stdin.readline

n, q = (int(i) for i in input().split())
tree = [[] for _ in range(n)]

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

ans = [0] * n

for _ in range(q):
    p, x = (int(i) for i in input().split())
    ans[p-1] += x

query = deque([(0, -1)])
while query:
    current_node, parent_node = query.popleft()
    current_value = ans[current_node]
    for node in tree[current_node]:
        if node == parent_node:
            continue
        else:
            ans[node] += current_value
            query.append([node, current_node])

print(*ans)

Measured memory_bytes: 65324
#include <cmath>
#include <iostream>
#include <string>
#include <time.h>
#include <stdio.h>
#include <iomanip>
using namespace std;

int main()
{
    int a, b;
    string opr;

    while (true)
    {
        cin >> a >> opr >> b;
        if (opr == "+")
        {
            cout << a + b << endl;
        }
        else if (opr == "-")
        {
            cout << a - b << endl;
        }
        else if (opr == "*")
        {
            cout << a * b << endl;
        }
        else if (opr == "/")
        {
            cout << a / b << endl;
        }
        else if (opr == "?")
        {
            return 0;
        }
    }
    return 0;
}


Measured memory_bytes: 3084
# N 個の頂点、N-1 個の辺なので K を根にした木構造に変換する

N = int(input())
T = {}
D = [None] * (N+1)
F = [True] * (N+1)

for n in range(N+1):
    T[n] = []

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

Q, K = map(int, input().split())

D[K] = 0
F[K] = False

L = [K]

while len(L) > 0:
    L_tmp = []
    for k in L:
        for t in T[k]:
            b, c = t
            if F[b] == True:
                D[b] = D[k] + c
                F[b] = False
                L_tmp.append(b)
    L = L_tmp

for q in range(Q):
    x, y = map(int, input().split())
    print(D[x] + D[y])


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

int main(){
    int n;cin>>n;
    vi v(n+1), w(n+1);
    rep(i,n)cin>>v[i+1]>>w[i+1];
    
    int q;cin>>q;
    vi s(q),tot(q);
    int mtot=0;
    rep(i,q){
        cin>>s[i]>>tot[i];
        mtot = max(mtot, tot[i]);
    }
    
    int size = min(n+1, 512);
    vv dp(size, vi(mtot+2, 0));
    
    for(int i=1; i<size; i++){
        for(int j=1; j<=mtot; j++){
            dp[i][j] = max(dp[i][j-1], dp[i/2][j]);
            if(j-w[i]>=0)
                dp[i][j] = max(dp[i][j], dp[i/2][j-w[i]]+v[i]);
        }
    }//dp[1~511][0~100000]のvが求まった
    
    rep(i,q){
        if(s[i]<size){
            cout << dp[s[i]][tot[i]] << endl;
            continue;
        }
        
        int len=0, b=s[i];
        while(b>511){
            b /= 2;
            len ++;
        }
        
        
        //int len = (int)log2(s[i])-8+1;
        
        int ans = 0;
        
        rep(k,1<<len){
            int vsum = 0, wsum = 0;
            b = s[i];
            rep(j,len){
                //if(wsum>tot[i])continue;
                if(k>>j & 1){
                    vsum += v[b];
                    wsum += w[b];
                }
                b /= 2;
            }
            
            if(wsum>tot[i])continue;
            ans = max(ans, vsum + dp[b][tot[i]-wsum]);
        }
        
        cout << ans << endl;
    }
    
    return 0;
}

Measured memory_bytes: 207316
let ans, n = ref 0, read_int ()
let fs, qs = Array.(make n 0, init n @@ fun _ -> Scanf.(scanf " %d" @@ fun a -> init a @@ fun _ -> scanf " %d %d" @@ fun a b -> a - 1, b))
let g _ = let c, b = ref 0, ref true in for i = 0 to n - 1 do if fs.(i) = 1 then (incr c; b := !b && Array.fold_left (fun b (x, y) -> b && fs.(x) = y) !b qs.(i)) done; if !b then !c else 0
let rec f i = if i >= n then ans := max !ans @@ g () else (fs.(i) <- 1; f (i + 1); fs.(i) <- 0; f (i + 1))
let _ = f 0; Printf.printf "%d\n" !ans

Measured memory_bytes: 4224
import sys
sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline
def main():
    n,q=map(int,input().split())
    graph=[[] for _ in range(n+1)]
    ab=[list(map(int,input().split())) for _ in range(n-1)]
    for a,b in ab:
        graph[a].append(b)
        graph[b].append(a)
    px=[list(map(int,input().split())) for _ in range(q)]
    seen=[0]*(n+1)
    ans=[0]*(n+1)
    for p,x in px:
        ans[p]+=x
    def dfs(i):
        seen[i]=1
        for li in graph[i]:
            if seen[li]==0:
                ans[li]+=ans[i]
                dfs(li)
    dfs(1)
    print(' '.join(map(str,ans[1:])))
if __name__ == '__main__':
    main()

Measured memory_bytes: 340540
#pragma GCC target ("avx2")
#pragma GCC optimize ("unroll-loops")
#pragma GCC optimize ("O3")
#include "bits/stdc++.h"
#include <unordered_set>
#include <unordered_map>
#include <random>
using namespace std;
typedef long long ll;
const ll MOD = 1'000'000'007LL; /*998'244'353LL;*/
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(), (x).end()
#define rep(i, n) for(int (i)=0; (i)<(n); (i)++)
const int dx[4]={ 1,0,-1,0 };
const int dy[4]={ 0,1,0,-1 };

int N, K;
vector<pair<ll,ll>> A;
vector<ll> p2, m2;

signed main(){
    cin >> N >> K;
    rep(i, N){
        ll a;
        cin >> a;
        if(a == 0) A.pb({ 0,1 });
        else A.pb({ abs(a), a/abs(a) });
    }
    sort(all(A));
    reverse(all(A));

    if(K == N){
        ll ans = 1;
        rep(i, N){
            ans *= (A[i].first*A[i].second + MOD) % MOD;
            ans %= MOD;
        }
        cout << ans << endl;
        return 0;
    }

    bool allM = true;
    rep(i, N) allM &= (A[i].second == -1);
    if(allM && K%2 == 1){
        ll ans = 1;
        reverse(all(A));
        rep(i, K){
            ans *= MOD-A[i].first;
            ans %= MOD;
        }
        cout << ans << endl;
        return 0;
    }
    if(allM && K%2 == 0){
        ll ans = 1;
        rep(i, K){
            ans *= (A[i].first*A[i].second + MOD) % MOD;
            ans %= MOD;
        }
        cout << ans << endl;
        return 0;
    }

    int cnt = 0;
    rep(i, K){
        if(A[i].second == -1) cnt++;
    }
    if(cnt%2 == 0){
        ll ans = 1;
        rep(i, K) ans = ans * A[i].first % MOD;
        cout << ans << endl;
    }
    else{
        int p = -1, m = -1;
        rep(i, K){
            if(A[i].second == 1) p = i;
            if(A[i].second == -1) m = i;
        }
        ll ans = 1;
        rep(i, K){
            if(i == p || i == m) continue;
            ans = ans * A[i].first % MOD;
        }
        int p2 = -1, m2 = -1;
        for(int i=N-1; i>=K; i--){
            if(A[i].second == 1) p2 = i;
            if(A[i].second == -1) m2 = i;
        }

        if(p == -1){
            ans *= A[p2].first;
            ans %= MOD;
            cout << ans << endl;
            return 0;
        }
        if(p == -1 || p2 == -1){
            ans *= A[m].first;
            ans %= MOD;
            ans *= A[m2].first;
            ans %= MOD;
            cout << ans << endl;
            return 0;
        }
        if(m == -1 || m2 == -1){
            ans *= A[p].first;
            ans %= MOD;
            ans *= A[p2].first;
            ans %= MOD;
            cout << ans << endl;
            return 0;
        }

        ll x1 = A[m].first*A[m2].first;
        ll x2 = A[p].first*A[p2].first;
        cout << max(x1, x2)%MOD * ans % MOD << endl;
    }
}

Measured memory_bytes: 7380
#include<iostream>
#include<cstdio>
using namespace std;
int n,k,ans,mx;
int gcd(int x,int y)
{
	if(y==0)return x;
	return gcd(y,x%y);
}
int main()
{
	scanf("%d%d",&n,&k);
	for(int i=1;i<=n;i++)
	{
		int x;
		scanf("%d",&x);
		mx=max(mx,x);
		if(i==1)ans=x;else ans=gcd(ans,x);
	}
	if(k<=mx && k%ans==0)printf("POSSIBLE");else printf("IMPOSSIBLE");
	return 0;
}

Measured memory_bytes: 256