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

using namespace std;

char S[25][25];
bool visited[25][25];
int H, W;
int mx = 0;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};

struct node {
	int x, y, t;
	node(int x_, int y_, int t_) {
		x = x_;
		y = y_;
		t = t_;
	}
};

void dfs(int x, int y) {
	memset(visited, false, sizeof(visited));
	queue<node> q;
	node n = node(x, y, 0);
	q.push(n);
	visited[x][y] = true;

	while (!q.empty()) {
		node now = q.front();
		q.pop();
		for (int i = 0; i < 4; i++) {
			int x2 = now.x + dir[i][0];
			int y2 = now.y + dir[i][1];
			if (0 <= x2 && x2 < H && 0 <= y2 && y2 < W && !visited[x2][y2] && S[x2][y2] != '#') {
				node next = node(x2, y2, now.t + 1);
				q.push(next);
				visited[x2][y2] = true;
				mx = max(mx, now.t + 1);
			}
		}
	}
}

int main() {
	cin >> H >> W;
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			cin >> S[i][j];
		}
	}
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) {
			if (S[i][j] == '#') {
				continue;
			}
			dfs(i, j);
		}
	}
	cout << mx << endl;
	return 0;
}

Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) FOR(i, 0, n)
#define FOR(i, a, b) for(int i=(a); i<(b); i++)

#define M 17
struct segtree{
	int a[1<<(M+1)];
	const int INIT=INT_MAX;
	void init(){
		fill(a, a+(1<<(M+1)), INIT);
	}

	void set(int p, int x){
		a[(1<<M)+p]=x;
		for(int i=M-1; i>=0; i--){
			int k=1<<(M-i);
			int j=p/k;
			a[(1<<i)+j]=min(
					a[(1<<(i+1))+j*2+0],
					a[(1<<(i+1))+j*2+1]);
		}
	}

	int get(int l, int r, int p=0, int q=0){
		int k=1<<(M-p);
		int f=k*q, g=k*(q+1);
		int ret;
		if(r<=f || g<=l){
			ret=INIT;
		}else if(l<=f && g<=r){
			ret=a[(1<<p)+q];
		}else{
			ret=min(
					get(l, r, p+1, q*2+0),
					get(l, r, p+1, q*2+1));
		}
		// printf("get(%d, %d, %d, %d)=%d\n", l, r, p, q, ret);
		return ret;
	}
};

segtree t;

int main(){
	int n, q;
	scanf("%d%d", &n, &q);
	t.init();
	REP(i, q){
		int c, x, y;
		scanf("%d%d%d", &c, &x, &y);
		if(c==0) t.set(x, y);
		if(c==1) printf("%d\n", t.get(x, y+1));
	}
}

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

using namespace std;

using ll = long long;
using ld = long double;

const int INF = (1 << 30) - 1;
const ll INF64 = ((ll)1 << 62) - 1;
const double PI = 3.1415926535897932384626433832795;

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

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

	int h, w, d;
	cin >> h >> w >> d;

	vector<int> x(h * w + 1), y(h * w + 1);
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			int a;
			cin >> a;

			x[a] = j;
			y[a] = i;
		}
	}

	vector<int> dd(h * w + 1);
	for (int i = d + 1; i <= h * w; i++) {
		dd[i] = dd[i - d] + abs(x[i] - x[i - d]) + abs(y[i] - y[i - d]);
	}

	int q;
	cin >> q;
	for (int i = 0; i < q; i++) {
		int l, r;
		cin >> l >> r;
		cout << dd[r] - dd[l] << endl;
	}
	return 0;
}


Measured memory_bytes: 2176
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,a) for(int i=0;i<(a);i++)
const ll MOD=1000000007;

int main(){
  int N; cin>>N;
  int B[N]; rep(i,N) cin>>B[i];
  int A[N],use[N]={};
  rep(i,N){
    int cnt=0,x=-1;
    rep(j,N){
      if(use[j]) continue;
      if(++cnt==B[j]) x=j;
    }
    if(x==-1){
      cout<<-1<<endl;
      return 0;
    }
    A[i]=B[x];
    use[x]=1;
  }
  rep(i,N) cout<<A[N-1-i]<<endl;
  return 0;
}


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAXN = 500;
int dp[500][500];
int n, m, q;

int main() {
    ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
    memset(dp, 0, sizeof dp);
    cin >> n >> m >> q;
    while(m--) {
        int l, r;
        cin >> l >> r;
        --l, --r;
        ++dp[l][r];
    }
    for(int i = 0; i < n - 1; ++i) {
        dp[i][i+1] += dp[i][i] + dp[i+1][i+1];
    }
    for(int len = 3; len <= n; ++len) {
        for(int i = 0, j = i + len - 1; j < n; ++i, ++j) {
            dp[i][j] += dp[i+1][j] + dp[i][j-1] - dp[i+1][j-1];
        }
    }
    while(q--) {
        int l, r;
        cin >> l >> r;
        --l, --r;
        cout << dp[l][r] << "\n";
    }
    return 0;
}

Measured memory_bytes: 1920
#!/usr/bin/env python3

import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)

N = int(input())
B = list(map(int, input().split()))

INF = float('inf')
B.append(INF)
B.insert(0, INF)

count = 0
for i in range(N):
    a = min(B[i], B[i+1])
    count += a

print(count)



Measured memory_bytes: 9152
import java.util.Scanner;

public class Main {

	private static Scanner sc;

	public static void main(String[] args) {

		sc = new Scanner(System.in);

		//料理の種類の合計をセット
		int intDishTotal = sc.nextInt();

		//食べた料理の順番をセット
		int[] intArrEatOrder = CreateArrayFromInput(intDishTotal);

		//各料理の満足度Bをセット
		int[] intArrSatisfactionB = CreateArrayFromInput(intDishTotal);

		//各料理の満足度Cをセット
		int[] intArrSatisfactionC = CreateArrayFromInput(intDishTotal - 1);

		//満足度合計
		int intSatisFactionSum = 0;

		//料理No.履歴（前回食べた料理No.）
		int intDishNoHistory = 0;

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

			//料理No.を取得
			int intDishNo = intArrEatOrder[i];

			//満足度Bを追加
			intSatisFactionSum += intArrSatisfactionB[intDishNo - 1];

			if(intDishNoHistory != 0 && intDishNoHistory == (intDishNo - 1)) {

				//満足度Cを追加
				intSatisFactionSum += intArrSatisfactionC[intDishNoHistory - 1];
			}

			//料理No.履歴を更新
			intDishNoHistory = intDishNo;

		}

		//アウトプット
		System.out.println(intSatisFactionSum);

	}

	//-----------------------------------------------------------
	//	コンソールで入力した値から配列を生成する
	//-----------------------------------------------------------
	private static int[] CreateArrayFromInput(int intInCount) {

		int[] intArrRet = new int[intInCount];

		for (int i = 0; i < intInCount; i++) {
			intArrRet[i] = sc.nextInt();
		}

		return intArrRet;
	}

}


Measured memory_bytes: 35828
#include <iostream>
#include <algorithm>
using namespace std;
 
int main()
{
    string str;
    cin  >> str;
    for (int i = 0; i < 4; ++i) cout << str[i];
    cout << " ";
    for (int i = 4; i < 12; ++i) cout << str[i]; cout << endl;
 
    return 0;
}

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

import math

theta = min(abs(30*H-5.5*M),360-abs(30*H-5.5*M))
cos = math.cos(math.radians(theta))

d = math.sqrt(math.pow(A,2)+math.pow(B,2)-2*A*B*cos)

print(d)

Measured memory_bytes: 9568
#include<bits/stdc++.h>
using namespace std;
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
#define eb emplace_back
#define ALL(A) A.begin(),A.end()
#define RALL(A) A.rbegin(),A.rend()
typedef long long LL;
typedef pair<LL,LL> P;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return 1; } return 0; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return 1; } return 0; }
template<typename T> T gcd(T a,T b){return b?gcd(b,a%b):a;}
const LL mod=1000000007;
const LL LINF=1LL<<62;
const int INF=1<<30;
int dx[]={1,0,-1,0,1,-1,1,-1};
int dy[]={0,1,0,-1,1,-1,-1,1};



int main(){
    LL n;cin >> n;
    LL ans = 0;
    for (LL i = 1; i <= n; i++) {
        for (LL j = 1; i * j <= n; j++) {
            ans += i * j;
        }
    }
    cout << ans << endl;
    return 0;
}


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

int main() {
    int N; cin >> N;
    string A, B, C; cin >> A >> B >> C;
    
    int res = 0;
    for(int i=0; i<N; ++i) {
        if(A[i] != B[i] && B[i] != C[i] && C[i] != A[i]) res += 2;
        else if((A[i] == B[i] && B[i] != C[i]) || (B[i] == C[i] && C[i] != A[i]) || (C[i] == A[i] && A[i] != B[i])) res += 1;
    }
    cout << res << endl;
}

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

int cPrime(int x)
{

	if(x%2==0) return 1;
	int i, len=sqrt(x);

	for(i=3;i<=len;i+=2)
	{
		if(x%i==0 && x!=i)
			return 1;
	}

	return 0;
}

int main()
{
	int a,count=0;

	scanf("%d",&a);

	while(a--)
	{
		int x;
		scanf("%d",&x);

		if((cPrime(x)==0) || x==2)
			count++;
	}

	printf("%d\n",count);

	return 0;
}



Measured memory_bytes: 2120
use std::io;
use std::cmp;
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::collections::HashSet;

fn read_line() -> String {
    let mut buf = String::new();
    io::stdin().read_line(&mut buf).ok();
    buf
}

fn parse(s: &str) -> usize {
    if s == "00" {
        0
    } else {
        s.parse().unwrap()
    }
}


fn main() {
    let s = read_line();
    let s = s.trim();

    let (yy, mm) = s.split_at(2);

    let y = parse(yy);
    let m = parse(mm);

    let mut valid_yymm = false;
    let mut valid_mmyy = false;

    if m >= 1 && m <= 12 {
        valid_yymm = true;
    }
    if y >= 1 && y <= 12 {
        valid_mmyy = true;
    }

    if valid_mmyy && valid_yymm {

        println!("AMBIGUOUS");
    } else if valid_yymm {
        println!("YYMM");
    } else if valid_mmyy {
        println!("MMYY");
    } else {
        println!("NA");
    }
}


Measured memory_bytes: 4352
N,T = map(int,input().split())
A = list(map(int,input().split()))
ar = A[::-1]
maxa = ar[0]
diff = 0
count = 0
for i in ar:
    if maxa < i:
        maxa = i
    else:
        if maxa - i == diff:
            count += 1
        elif maxa - i > diff:
            count = 1
            diff = maxa -i
print(count)

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

int main(){
    int ans=0;
    int n;
    cin >> n;
    char ch;

    for (int i = 0; i < n; i++){
        cin >> ch;
        if(ch=='Y'){
            std::cout << "Four" << '\n';
            return  0;
        }
    }
    //cout <<fixed<<setprecision(16)<< << endl;
    cout << "Three" << endl;
    //if(flag==1)cout << "Yes" <<endl;
    //else cout << "No" <<endl;
    
    return 0;
}


Measured memory_bytes: 256
import math
def P(n, r):
    return math.factorial(n)//math.factorial(n-r)
def C(n, r):
    return P(n, r)//math.factorial(r)

N = int(input())
moji =[]
for i in range(N):
    a = sorted(input())
    moji.append(''.join(a))


dic = {}
for i in moji:
    if i in dic:
        dic[i] += 1
    else:
        dic[i] = 1

ans = 0
for value in dic.values():
    if value >=2:
        a= C(value, 2)
        ans+=a

print(ans)



Measured memory_bytes: 102380
#include<iostream>
#include<string>
#include<vector>
#include<list>
#include<cmath>
#include<algorithm>
#include<cstdio>
#include<set>
#include<map>
#include<queue>
#include<cstring>
#include<sstream>
using namespace std;

typedef long long ll;

int main() {
  int N; cin >> N;
  string s,t; cin >> s >> t;
  int ans = 2*N;
  int l = 2*N;
  for ( int i = 0; i < N; i++ ) {
    l = 2*N;
    for ( int j = i; j < N; j++ ) {
      if ( s[j] == t[j-i] ) {
	l--;
	if ( j == N-1  )  ans = min(l,ans);

      }else {
	break;
      }
    }
  }
  cout << ans << endl;
  return 0;
}


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

int main() {
 int N;
  cin >> N;
 for( int i = 0 ; i < N ; i++ ) {
   string Color;
   cin >> Color;
   if( Color == "Y") {
     cout << "Four" << endl;
     break;
   }
   if( N<=i+1 && Color != "Y"){
     cout << "Three"<< endl;
   }
 }
}

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

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define FOR(x,to) for(x=0;x<(to);x++)
#define FORR(x,arr) for(auto& x:arr)
#define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++)
#define ALL(a) (a.begin()),(a.end())
#define ZERO(a) memset(a,0,sizeof(a))
#define MINUS(a) memset(a,0xff,sizeof(a))
//-------------------------------------------------------

string S;

void solve() {
	int i,j,k,l,r,x,y; string s;
	
	cin>>S;
	FOR(i,S.size()-1) if(S.substr(i,2)=="AC") return _P("Yes\n");
	_P("No\n");
	
}


int main(int argc,char** argv){
	string s;int i;
	if(argc==1) ios::sync_with_stdio(false), cin.tie(0);
	FOR(i,argc-1) s+=argv[i+1],s+='\n'; FOR(i,s.size()) ungetc(s[s.size()-1-i],stdin);
	cout.tie(0); solve(); return 0;
}


Measured memory_bytes: 256
#include<stdio.h>
#include<algorithm>
int IN(void)
{
  int x=0,f=0,c=getchar();while(c<48||c>57){f^=c==45,c=getchar();}
  while(c>47&&c<58){x=x*10+c-48,c=getchar();}return f?-x:x;
}
int main(void)
{
  int N=IN(),K=IN(),P[1000]={0},sum=0;
  for(int i=0;i<N;i++){P[i]=IN();}
  std::sort(P,P+N);
  for(int i=0;i<K;i++){sum+=P[i];}
  return printf("%d\n",sum),0;
}

Measured memory_bytes: 1608
#include <iostream>

using namespace std;

int main()
{
    int n,m,d,e;
    cin >> n >> m;
    int a[n][m],b[m],c[n];
    for(int i=0;i<n;++i){
        for(int j=0;j<m;++j){
            cin >> d;
            a[i][j]=d;
        }
    }
    for(int j=0;j<m;++j){
        cin >> e;
        b[j]=e;
    }
    for(int i=0;i<n;++i){
            c[i]=0;
    }
    for(int i=0;i<n;++i){
        for(int j=0;j<m;++j){
            c[i]+=(a[i][j]*b[j]);
        }
    }
    for (int i=0;i<n;++i){
        cout << c[i]<<endl;
    }
    return 0;

}



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

int main() {
  int N, Yen;
  cin >> N >> Yen;
  for(int i = 0; i <= N; i++){
    for(int j = 0; j <= N - i; j++){
      if(i * 10000 + j * 5000 + (N - i - j) * 1000 == Yen){
        cout << i << ' ' << j << ' ' << N - i - j << endl;
        return 0;
      }
    }
  }
  cout << -1 << ' ' << -1 << ' ' << -1 << endl;
}


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

int main() {
    const double PI = acos(-1.0);
    double a, b, x;
    cin >> a >> b >> x;
    x /= a;
    cout << fixed << setprecision(10);
    if (x > a*b/2) cout << atan2((a*b-x)*2, a*a) * 180 / PI << endl;
    else cout << atan2(b*b, x*2) * 180 / PI << endl;
}

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


//ll a[100005];
//vector<ll> cache(100005,-1);
//ll n;
//
//ll frog1(ll x)
//{
//	if(cache[x]!=-1)
//		return cache[x];
//	if(x>=n)
//		return INT_MAX;
//	if(x==n-1)
//		return 0;
//	else
//		return cache[x] = min( abs(a[x+1]-a[x])+frog1(x+1), abs(a[x+2]-a[x])+frog1(x+2));
//}
//
//int main()
//{
//	cin>>n;
//	for(int i=0;i<n;i++)
//	{
//		cin>>a[i];
//	}
//	cout<<frog1(0);
//	return 0;
//}

int main()
{
	ll n,k;
	cin>>n>>k;
	vector<int> a;
	for(int i=0;i<n;i++)
	{
		int x;
		cin>>x;
		a.push_back(x);
	}
	vector<int> dp(n,INT_MAX);
	dp[0] = 0;
	for(int i=0;i<n;i++)
	{
		for(int j=i+1;j<=i+k;j++)
		{
			if(j<n)
				dp[j] = min(dp[j],dp[i] + abs(a[j]-a[i]));
		}
	}
	cout<<dp[n-1];
	return 0;
}

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

#define mp make_pair
#define mt make_tuple
#define pb push_back
#define eb emplace_back
#define fi first
#define se second
#define ALL(a) begin(a), end(a)
#define SZ(a) ((int)(a).size())

#define REP(a, b) for (int a = 0; a < (b); a++)
#define FOR(a, b, c) for (int a = (b); a <= (c); a++)
#define REPD(a, b) for (int a = (b) - 1; a >= 0; a--)
#define FORD(a, b, c) for (int a = (b); a >= (c); a--)

#define MIN(a, b) (a) = min((a), (b))
#define MAX(a, b) (a) = max((a), (b))

#if defined(__GNUC__)
#define LIKELY(x) (__builtin_expect((x), 1))
#define UNLIKELY(x) (__builtin_expect((x), 0))
#else
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#endif  // defined(__GNUC__)

#ifdef __DEBUG
#define debug if (true)
#else
#define debug if (false)
#endif  // __DEBUG

template <typename... T>
using tpl = tuple<T...>;

#define DECLARE_TUPLE_ACCESSOR(TIDX) \
  struct TupleIndex_##TIDX##_t {};\
  template <typename... T>\
  typename tuple_element<TIDX, tuple<T...>>::type& operator/(tuple<T...>& t, TupleIndex_##TIDX##_t) { return get<TIDX>(t); }\
  template <typename... T>\
  const typename tuple_element<TIDX, tuple<T...>>::type& operator/(const tuple<T...>& t, TupleIndex_##TIDX##_t) { return get<TIDX>(t); }\
  constexpr TupleIndex_##TIDX##_t _##TIDX;

DECLARE_TUPLE_ACCESSOR(0)
DECLARE_TUPLE_ACCESSOR(1)
DECLARE_TUPLE_ACCESSOR(2)
DECLARE_TUPLE_ACCESSOR(3)

#undef DECLARE_TUPLE_ACCESSOR

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

template <typename T> using V = vector<T>;
template <typename T> using VV = vector<V<T>>;
template <typename T> using VVV = vector<VV<T>>;

template <typename T1, typename T2>
istream& operator>>(istream& is, pair<T1, T2> &p) {
  return is >> p.fi >> p.se;
}

#if __cplusplus > 201402L
template <typename... T, size_t... I>
istream& tupleInputImpl(istream &is, tuple<T...> &tpl, index_sequence<I...>) {
  return (is >> ... >> get<I>(tpl));
}

template <typename... T>
istream& operator>>(istream& is, tuple<T...> &tpl) {
  return tupleInputImpl(is, tpl, index_sequence_for<T...>{});
}
#endif  // __cplusplus > 201402L

void Main() {
  int h, w, a, b;
  cin >> h >> w >> a >> b;
  REP(i, h) {
    REP(j, w) {
      bool val = (j < a) ^ (i < b);
      putchar(val ? '1' : '0');
    }
    puts("");
  }
}

int main(int argc, char *argv[]) {
  if (argc > 1) {
    freopen(argv[1], "r", stdin);
  } else {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
  }
  Main();
}


Measured memory_bytes: 1280
def main():
    import sys
    input = sys.stdin.readline
    sys.setrecursionlimit(10000000)
    from collections import Counter, deque
    #from collections import defaultdict
    from itertools import combinations, permutations
    #from itertools import accumulate, product
    from bisect import bisect_left,bisect_right
    from math import floor, ceil
    #from operator import itemgetter

    #mod = 1000000007

    S = input().rstrip()
    T = input().rstrip()
    s = len(S)
    t = len(T)

    dp = [[0]*(t+1) for _ in range(s+1)]
    for i in range(s):
        for j in range(t):
            if S[i]==T[j]:
                dp[i+1][j+1]=dp[i][j]+1
            else:
                dp[i+1][j+1]=max(dp[i][j+1], dp[i+1][j])

    #復元
    res = ''
    while s != 0 and t != 0:
        if dp[s][t] == dp[s-1][t]:
            s -= 1
        elif dp[s][t] == dp[s][t-1]:
            t -= 1
        else:
            s -= 1
            t -= 1
            res = S[s] + res
    print(res)

if __name__ == '__main__':
    main()

Measured memory_bytes: 112860
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 1e5+5;

int g[N];
inline ll gcd(ll a,ll b){return b ?gcd(b,a%b) :a;}
 
inline ll cal(ll x){
	ll res = 0;
	while(x % 2 == 0){
		res++;
		x >>= 1;
	}
	return res;
}
 
int main()
{
    ll x,n,m,k,s;
	scanf("%lld%lld%lld",&n,&m,&x);
	s = x;
	k = x >> 1;
	g[1] = cal(k);
	
	for(int i = 2;i <= n;++i){
		scanf("%lld",&x);
		s = s/gcd(s,x)*x;
		x >>= 1;
		g[i] = cal(x);
		k = k/gcd(k,x)*x;
	}
	
	sort(g+1,g+n+1);
	if(g[1] != g[n]) printf("0\n");
	else printf("%lld\n",m/k-m/s);
    return 0;
}

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


int main()
{
	int car[10] = {}, b[100];
	int i = 0, cou = 0;
	while (cin >> b[i]) {
		if (b[i] != 0) {
			car[cou] = b[i];
			cou++;
		}
		if (b[i] == 0) {
			cout << car[cou - 1] << endl;
			cou--;
		}
		i++;
	}
    return 0;
}



Measured memory_bytes: 2992
def prime(p):
    ret = {}
    a = int(p ** 0.5)
    k = 2
    while(p > 1):
        if p % k == 0:
            p //= k
            ret[k] = ret.get(k, 0) + 1
        elif k > a:
            k = p
        else:
            k += 1
    return ret


n, p = map(int, input().split())
ret = prime(p)
# print(ret)
ans = 1
for i in list(filter(lambda x: ret[x] >= n, list(ret))):
    ans *= i ** (ret[i] // n)
print(ans)

Measured memory_bytes: 3188
#include <bits/stdc++.h>
#define fi first
#define se second
#define rep(i,n) for(int i = 0; i < (n); ++i)
#define rrep(i,n) for(int i = 1; i <= (n); ++i)
#define drep(i,n) for(int i = (n)-1; i >= 0; --i)
#define srep(i,s,t) for (int i = s; i < t; ++i)
#define rng(a) a.begin(),a.end()
#define rrng(a) a.rbegin(),a.rend()
#define maxs(x,y) (x = max(x,y))
#define mins(x,y) (x = min(x,y))
#define limit(x,l,r) max(l,min(x,r))
#define lims(x,l,r) (x = max(l,min(x,r)))
#define isin(x,l,r) ((l) <= (x) && (x) < (r))
#define pb push_back
#define eb emplace_back
#define sz(x) (int)(x).size()
#define pcnt __builtin_popcountll
#define uni(x) x.erase(unique(rng(x)),x.end())
#define show(x) cout<<#x<<" = "<<x<<endl;
#define print(x)cout<<x<<endl;
#define PQ(T) priority_queue<T,v(T),greater<T> >
#define bn(x) ((1<<x)-1)
#define dup(x,y) (((x)+(y)-1)/(y))
#define newline puts("")
#define v(T) vector<T>
#define vv(T) v(v(T))
using namespace std;
typedef long long int ll;
typedef unsigned uint;
typedef unsigned long long ull;
typedef pair<int,int> P;
typedef tuple<int,int,int> T;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<P> vp;
typedef vector<T> vt;

const int mod = 998244353;
struct mint {
  ll x; // typedef long long ll;
  mint(ll x=0):x((x%mod+mod)%mod){}
  mint operator-() const { return mint(-x);}
  mint& operator+=(const mint a) {
    if ((x += a.x) >= mod) x -= mod;
    return *this;
  }
  mint& operator-=(const mint a) {
    if ((x += mod-a.x) >= mod) x -= mod;
    return *this;
  }
  mint& operator*=(const mint a) {
    (x *= a.x) %= mod;
    return *this;
  }
  mint operator+(const mint a) const {
    mint res(*this);
    return res+=a;
  }
  mint operator-(const mint a) const {
    mint res(*this);
    return res-=a;
  }
  mint operator*(const mint a) const {
    mint res(*this);
    return res*=a;
  }
  mint pow(ll t) const {
    if (!t) return 1;
    mint a = pow(t>>1);
    a *= a;
    if (t&1) a *= *this;
    return a;
  }

  // for prime mod
  mint inv() const {
    return pow(mod-2);
  }
  mint& operator/=(const mint a) {
    return (*this) *= a.inv();
  }
  mint operator/(const mint a) const {
    mint res(*this);
    return res/=a;
  }
};

struct combination {
  vector<mint> fact, ifact;
  combination(int n):fact(n+1),ifact(n+1) {
    assert(n < mod);
    fact[0] = 1;
    for (int i = 1; i <= n; ++i) fact[i] = fact[i-1]*i;
    ifact[n] = fact[n].inv();
    for (int i = n; i >= 1; --i) ifact[i-1] = ifact[i]*i;
  }
  mint operator()(int n, int k) {
    if (k < 0 || k > n) return 0;
    return fact[n]*ifact[k]*ifact[n-k];
  }
};
int main() {
  int n,m,k;
  cin>>n>>m>>k;
  combination comb(n);
  mint ans = 0;
  mint tmp = m;
  for(int x = n-1;x >= 0; x--){
    if(x<=k)ans+=comb(n-1,x)*tmp;
    tmp*=(m-1);
  }
  cout<<ans.x<<endl;
  return 0;
}

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

typedef pair<int,int> P;
typedef pair<P, int> sP;

void solve(int N, int M, int C) {
    string start, goal;
    cin >> start >> goal;

    set<string> citys;
    vector<string> slist(N), elist(N);
    vector<int> edge(N);
    for (int i = 0; i < N; i++) {
        cin >> slist[i] >> elist[i] >> edge[i];
        citys.insert(slist[i]);
        citys.insert(elist[i]);
    }

    map<string,int> s_num;
    int _idx = 0;
    for (auto i : citys) {
        s_num[i] = _idx;
        _idx++;
    }

    vector<vector<P>> m(citys.size());
    for (int i = 0; i < N; i++) {
        m[s_num[slist[i]]].push_back(P(s_num[elist[i]], edge[i]));
        m[s_num[elist[i]]].push_back(P(s_num[slist[i]], edge[i]));
    }

    vector<int> store(M);
    for (auto& i : store) {
        string x;
        cin >> x;
        i = s_num[x];
    }
    

    vector<map<int,int>> dp(citys.size());
    dp[s_num[start]][C*10] = 0;

    priority_queue<sP, vector<sP>, greater<sP>> que;
    que.push(sP(P(0, C*10), s_num[start]));

    while (que.size() > 0) {
        auto sp = que.top(); que.pop();
        int now = sp.second;
        int cost = sp.first.first;
        int cap = sp.first.second;

        if (dp[now].size() > 0
            && dp[now].find(cap) != dp[now].end()
            && dp[now][cap] < cost) continue;

        if (now == s_num[goal]) break;

        for (auto city : m[now]) {
            int next = city.first;
            int dist = city.second;
            int _cap = cap - dist;

            if (_cap < 0) continue;
            if (find(store.begin(), store.end(), next) != store.end()) _cap = C * 10;
            
            if (dp[next].size() == 0 || dp[next].find(_cap) == dp[next].end()) {
                dp[next][_cap] = cost + dist;
                que.push(sP(P(cost + dist, _cap), next));
            } else if (dp[next][_cap] > cost + dist) {
                dp[next][_cap] = cost + dist;
                que.push(sP(P(cost + dist, _cap), next));
            }
        }
    }

    if (dp[s_num[goal]].size() == 0) cout << -1 << endl;
    else {
        int ans = 1 << 28;
        for (auto i : dp[s_num[goal]]) ans = min(ans, i.second);
        cout << ans << endl;
    }
}

int main() {
    int N, M, C;
    while (cin >> N >> M >> C, N || M || C) solve(N, M, C);

    return 0;
}

Measured memory_bytes: 200192
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <string>
#include <set>
#include <unordered_set>
#include <map>
#include <unordered_map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <functional>
#include <iterator>
#include <limits>
#include <numeric>
#include <utility>
#include <type_traits>
#include <cmath>
#include <cassert>
#include <cstdio>

using namespace std;
using namespace placeholders;

using LL = long long;
using ULL = unsigned long long;
using VI = vector< int >;
using VVI = vector< vector< int > >;
using VS = vector< string >;
using ISS = istringstream;
using OSS = ostringstream;
using PII = pair< int, int >;
using VPII = vector< pair< int, int > >;
template < typename T = int > using VT = vector< T >;
template < typename T = int > using VVT = vector< vector< T > >;
template < typename T = int > using LIM = numeric_limits< T >;

template < typename T > inline istream& operator>>( istream &s, vector< T > &v ){ for ( T &t : v ) { s >> t; } return s; }
template < typename T > inline ostream& operator<<( ostream &s, const vector< T > &v ){ for ( int i = 0; i < int( v.size() ); ++i ){ s << ( " " + !i ) << v[i]; } return s; }
template < typename T > inline T fromString( const string &s ) { T res; istringstream iss( s ); iss >> res; return res; }
template < typename T > inline string toString( const T &a ) { ostringstream oss; oss << a; return oss.str(); }

#define NUMBERED( name, number ) NUMBERED2( name, number )
#define NUMBERED2( name, number ) name ## _ ## number
#define REP1( n ) REP2( NUMBERED( REP_COUNTER, __LINE__ ), n )
#define REP2( i, n ) REP3( i, 0, n )
#define REP3( i, m, n ) for ( int i = ( int )( m ); i < ( int )( n ); ++i )
#define GET_REP( a, b, c, F, ... ) F
#define REP( ... ) GET_REP( __VA_ARGS__, REP3, REP2, REP1 )( __VA_ARGS__ )
#define FOR( e, c ) for ( auto &&e : c )
#define ALL( c ) begin( c ), end( c )
#define AALL( a ) ( remove_all_extents< decltype( a ) >::type * )a, ( remove_all_extents< decltype( a ) >::type * )a + sizeof( a ) / sizeof( remove_all_extents< decltype( a ) >::type )
#define DRANGE( c, p ) begin( c ), begin( c ) + ( p ), end( c )

#define SZ( v ) ( (int)( v ).size() )
#define EXIST( c, e ) ( ( c ).find( e ) != ( c ).end() )

template < typename T > inline bool chmin( T &a, const T &b ){ if ( b < a ) { a = b; return true; } return false; }
template < typename T > inline bool chmax( T &a, const T &b ){ if ( a < b ) { a = b; return true; } return false; }

#define PB push_back
#define EM emplace
#define EB emplace_back
#define BI back_inserter

#define MP make_pair
#define fst first
#define snd second

#define DUMP( x ) cerr << #x << " = " << ( x ) << endl

const VS STRINGS = {
	"dream",
	"dreamer",
	"erase" ,
	"eraser"
};

int dp[ 1 << 17 ];

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

	string S;
	cin >> S;

	const int L = SZ( S );

	dp[0] = 1;

	REP( i, L )
	{
		FOR( s, STRINGS )
		{
			if ( S.substr( i, SZ( s ) ) == s )
			{
				dp[ i + SZ( s ) ] |= dp[i];
			}
		}
	}

	cout << ( dp[L] ? "YES" : "NO" ) << endl;

	return 0;
}


Measured memory_bytes: 848
// 2012/12/13 Tazoe

#include <iostream>
using namespace std;

int no(int C[10002], int i, int c)
{
	int p = i-1;
	int q = i+1;

	int nc = 1;

	while(C[p]==c){
		nc++;
		p--;
	}
	while(C[q]==c){
		nc++;
		q++;
	}

	if(nc<4)
		return 0;

	int sum = nc;

	while(C[p]!=0&&C[q]!=0&&C[p]==C[q]){
		c = C[p];
		nc = 0;

		while(C[p]==c){
			nc++;
			p--;
		}
		while(C[q]==c){
			nc++;
			q++;
		}

		if(nc<4)
			break;

		sum += nc;
	}

	return sum;
}

int main()
{
while(true){
	int N;
	cin >> N;

if(N==0)
break;

	int C[10002];
	C[0] = 0;
	for(int i=1; i<=N; i++){
		cin >> C[i];
	}
	C[N+1] = 0;

	int M = N;
	for(int i=1; i<=N; i++){
		for(int j=1; j<=3; j++){
			int n = no(C, i, j);

			if(N-n<M){
				M = N-n;
			}
		}
	}

	cout << M << '\n';
}

	return 0;
}

Measured memory_bytes: 1200
#include <iostream>
using namespace std;
int main()
{
	int R;
	cin>>R; 
	switch (R/400){
		case 0: case 1: case 2:
			cout<<"ABC"<<endl;break;
		case 3: case 4: case 5: case 6: 
		    cout<<"ARC"<<endl;break;
		default :
			cout<<"AGC"<<endl;break;
	} 
	return 0;
}

Measured memory_bytes: 256
import sys
from bisect import bisect as br
A, B, Q = map(int, input().split())
inf = 10**11
S = [-inf] + [int(sys.stdin.readline()) for _ in range(A)] + [inf]
T = [-inf] + [int(sys.stdin.readline()) for _ in range(B)] + [inf]
X = [int(sys.stdin.readline()) for _ in range(Q)]

StoT = [0]*A
for i, s in enumerate(S[1:-1]):
    x = br(T, s)
    StoT[i] = (s, min(s - T[x-1], T[x] - s))

TtoS = [0]*B
for i, t in enumerate(T[1:-1]):
    x = br(S, t)
    TtoS[i] = (t, min(t - S[x-1], S[x] - t))

M = [(-inf, inf)] + TtoS + StoT + [(inf, inf)]
M.sort()
Mk , Mv = list(map(list, zip(*M)))
for x in X:
    idx = br(Mk, x)
    print(min(Mk[idx] - x + Mv[idx], x - Mk[idx-1] + Mv[idx-1]))


Measured memory_bytes: 109408
#include <algorithm>
#include <cstdio>
#include <set>
#include <vector>

using namespace std;

struct Edge {
  int s;
  int t;
  int w;
  Edge(int s, int t, int w) {
    this->s = s;
    this->t = t;
    this->w = w;
  }
};

bool cmp(const Edge& e1, const Edge& e2) {
  return e1.w < e2.w;
}

vector<Edge> edges;
vector<int> dsj;

int V, E;
int res;
int resv;

void input() {
  scanf("%d %d", &V, &E);
  for (int i = 0; i < E; i++) {
    int s, t, w;
    scanf("%d %d %d", &s, &t, &w);
    edges.emplace_back(s, t, w);
  }
  for (int i = 0; i < V; i++) {
    dsj.push_back(i);
  }
}

int dsjof(int x) {
  vector<int> updates;
  while (dsj[x] != x) {
    updates.push_back(x);
    x = dsj[x];
  }
  for (int i : updates) {
    dsj[i] = x;
  }
  return x;
}

void merge(int a, int b) {
  int p1 = dsjof(a);
  int p2 = dsjof(b);
  if (p1 < p2) {
    dsj[p1] = p2;
  } else {
    dsj[p2] = p1;
  }
}

void printDsj() {
  printf("===\n");
  for (int i = 0; i < V; i++) {
    printf("\t%d", i);
  }
  printf("\n");
  for (int i = 0; i < V; i++) {
    printf("\t%d", dsj[i]);
  }
  printf("\n===\n");
}

void solve() {
  // sort edges by weight
  sort(edges.begin(), edges.end(), cmp);

  for (const auto& e : edges) {
    if (resv == V) {
      break;
    }
    //printDsj();
    if (dsjof(e.s) != dsjof(e.t)) {
      //printf("Including edge %d %d %d\n", e.s, e.t, e.w);
      resv += 1;
      if (resv == 1) {
        resv += 1;
      }
      merge(e.s, e.t);
      res += e.w;
    }
  }
}

void output() {
  printf("%d\n", res);
  // for (const auto& x : edges) {
  //   printf("s:%d t:%d w:%d\n", x.s, x.t, x.w);
  // }
}

int main() {
  input();
  solve();
  output();
}

Measured memory_bytes: 2552
#include <iostream>
#include <vector>
#include <string>
#include <math.h>
#include <algorithm>
#include <numeric>
using namespace std;
#define rep(i, n) for (int i = 0; i < (n); i++)

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

    string ab = "";
    rep(i, b) ab = ab + to_string(a);
    string ba = "";
    rep(i, a) ba = ba + to_string(b);

    if (a <= b) cout << ab << endl;
    else cout << ba << endl;
}

Measured memory_bytes: 256
#include<iostream>
#include<algorithm>
#include<cmath>
#include<string>
#include<array>
#include<vector>
#include<functional>
#include<unordered_map>
#include<map>
#include<numeric>
#include<limits>
#include<utility>
#include<queue>
#include<random>
using namespace std;

int main(void) {
	int N, count = 0, max = 0;
	string S;
	cin >> N >> S;
	for (int i = 0; i < N; i++) {
		if (S[i] == 'I') {
			count++;
			if (count > max)
				max = count;
		}
		else
			count--;
	}
	cout << max << endl;

	return 0;
}

Measured memory_bytes: 256
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <climits>
#include <cstring>
#include <cassert>


using namespace std;
#define SZ(x) (int)(x.size())
#define REP(i, n) for(int i=0;i<n;++i)
#define FOR(i, a, b) for(int i=a;i<b;++i)
#define RREP(i, n) for(int i=n-1;i>=0;--i)
#define RFOR(i, a, b) for(int i=b-1;i>=a;--i)

#define all(x) begin(x),end(x)
#define dump(x) cerr<<#x<<" = "<<(x)<<endl
#define debug(x) cerr<<#x<<" = "<<(x)<<" (L"<<__LINE__<<")"<< endl;

using ll = long long;
using vi = vector<int>;
using vvi = vector<vi>;
using vll = vector<ll>;
using vvll = vector<vll>;
using P = pair<int, int>;
const double eps = 1e-8;
const ll MOD = 1000000007;
const int INF = INT_MAX / 2;
const ll LINF = LLONG_MAX / 2;

template<class T>
bool chmax(T &a, const T &b) {
    if (a < b) {
        a = b;
        return true;
    }
    return false;
}

template<class T>
bool chmin(T &a, const T &b) {
    if (b < a) {
        a = b;
        return true;
    }
    return false;
}


template<typename T1, typename T2>
ostream &operator<<(ostream &os, const pair<T1, T2> p) {
    os << p.first << ":" << p.second;
    return os;
}

template<class T>
ostream &operator<<(ostream &os, const vector<T> &v) {
    os << "[";
    REP(i, SZ(v)) {
        if (i) os << ", ";
        os << v[i];
    }
    return os << "]";
}

template<class T1, class T2>
ostream &operator<<(ostream &os, const map<T1, T2> &mp) {
    os << "[";
    for (auto it = mp.begin(); it != mp.end(); ++it) {
        if (it != mp.begin()) {
            os << ", ";
        }
        os << *it;
    }
    return os << "]";
}

// edit

bool solve() {
    int n, m;
    cin >> n >> m;
    if (n == 0) return false;

    vector<int> a(n);
    REP(i, n) cin >> a[i];

    int ans = 0;
    for (int i = 0; i < n; ++i) {
        for (int j = i + 1; j < n; ++j) {
            int tmp = a[i] + a[j];
            if (tmp <= m) {
                chmax(ans, tmp);
            }
        }
    }
    if (ans == 0) {
        cout << "NONE" << endl;
        return true;
    }
    cout << ans << endl;

    return true;
}

int main() {
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout << fixed << setprecision(10);
//    std::ifstream in("input.txt");
//    std::cin.rdbuf(in.rdbuf());

    while (solve());


    return 0;
}



Measured memory_bytes: 3124
N = int(input())
T,A = map(int,input().split())
H = list(map(int,input().split()))
B = abs(A-(T-0.006*H[0]))
for i in range(N):
    C = abs(A-(T-0.006*H[i]))
    if B>=C:
        B = C
        ans = i+1
print(ans)


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

class Dice{
public:
    int Now[7], Will[7];
    
    Dice(int N[]){
        for(int i=1; i<7; i++){
            Now[i]=N[i];
            Will[i]=N[i];
        }
    }
    
    void move_S(){
        Will[1] = Now[5];
        Will[2] = Now[1];
        Will[6] = Now[2];
        Will[5] = Now[6];
        
        for(int i=1; i<7; i++){
            Now[i] = Will[i];
        }
    }
    
    void move_E(){
        Will[1] = Now[4];
        Will[3] = Now[1];
        Will[6] = Now[3];
        Will[4] = Now[6];
        
        for(int i=1; i<7; i++){
            Now[i] = Will[i];
        }
    }
    
    void move_N(){
        Will[1] = Now[2];
        Will[5] = Now[1];
        Will[6] = Now[5];
        Will[2] = Now[6];
        
        for(int i=1; i<7; i++){
            Now[i] = Will[i];
        }
    }
    
    void move_W(){
        Will[1] = Now[3];
        Will[4] = Now[1];
        Will[6] = Now[4];
        Will[3] = Now[6];
        
        for(int i=1; i<7; i++){
            Now[i] = Will[i];
        }
    }

    void turn(){
        Will[2] = Now[4];
        Will[3] = Now[2];
        Will[5] = Now[3];
        Will[4] = Now[5];

        for(int i=1; i<7; i++){
            Now[i] = Will[i];
        }
    }
    
    int top(){
        return Now[1];
    }

    int front(){
        return Now[2];
    }

    int right(){
        return Now[3];
    }
};


int main(){
    int Face[7];
    for(int i=1; i<7; i++){
        cin >> Face[i];
    }
    int q;
    cin >> q;

    Dice dice(Face);

    for(int i=0; i<q; i++){
        int top, front, right;
        cin >> top >> front;

        if(dice.top() != top){
            dice.move_N();
            if(dice.top() != top){
                dice.move_W();
                if(dice.top() != top){
                    dice.move_W();
                    if(dice.top() != top){
                        dice.move_W();
                        if(dice.top() != top){
                            dice.move_N();
                        }
                    }
                }
            }
        }

        if(dice.front() != front){
            dice.turn();
            if(dice.front() != front){
                dice.turn();
                if(dice.front() != front){
                    dice.turn();
                }
            }
        }

        cout << dice.right() << endl;
    }
    
return 0;
}


Measured memory_bytes: 3096
#include<bits/stdc++.h>
using namespace std;
int main(){
 string s;
  cin>>s;
  if((s[0]=='R'&&s[1]=='R'&&s[2]!='R')||(s[2]=='R'&&s[1]=='R'&&s[0]!='R'))
  cout<<"2";
  else if(s[0]=='R'&&s[1]=='R'&&s[2]=='R')
      cout<<"3";
  else if(s[0]=='R'||s[1]=='R'||s[2]=='R')
    cout<<"1";
  else
    cout<<"0";
    return 0;
}


Measured memory_bytes: 3608
#include <iostream>
using namespace std;
int main()
{
    int n;
    cin >> n;
    int l,m=0,sum=0;
    int i=0;
    while(i<n){
        i++;
        cin >> l;
        if(m<l) m=l;
        sum+=l;
    }
    if(sum>2*m)
        cout << "Yes" << endl;
    else
        cout << "No" << endl;
    return 0;
}


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

using namespace std;

int main()
{
	long long n,ans=0;
	cin >> n;
	// n=km+m=k(m+1)
	// m+1=div
	// m=div-1
	for(long long i=1;i*i<=n;i++)
	{
		if(n%i) continue;
		long long a=i-1;
		if(a&&n/a==n%a) ans+=a;
		if(n/i==i) continue;
		a=n/i-1;
		if(n/a==n%a) ans+=a;
	}
	cout << ans << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <string>
#include<algorithm>
#include <vector>
#include<stack>
#include<queue>
#include<list>
#include<set>
#include<map>
using namespace std;



int main() {

	int N,max_a,min_a;
	cin >> N;
	int a[N];
	for (int i = 0; i < N; i++) cin >> a[i];
	max_a = a[0];
	min_a = a[0];
	for (int i = 1; i < N; i++) {
		if (a[i] > max_a) max_a = a[i];
		if (min_a > a[i]) min_a = a[i];
	}
	cout << max_a - min_a << endl;

	return 0;
}

Measured memory_bytes: 256
S=input()
W=["dream","dreamer","erase","eraser"]

ans="YES"
while len(S)>0:
  if S.endswith(W[0]):
    S=S[:-len(W[0])]
  elif S.endswith(W[1]):
    S=S[:-len(W[1])]
  elif S.endswith(W[2]):
    S=S[:-len(W[2])]
  elif S.endswith(W[3]):
    S=S[:-len(W[3])]
  else:
    ans="NO"
    break
    
print(ans)

Measured memory_bytes: 3188
W,H=map(int,input().split())
P=[int(input()) for i in range(W)]
Q=[int(input()) for i in range(H)]
R=[]
for i in range(W):
  R.append((P[i],0))
for i in range(H):
  R.append((Q[i],1))
P=0
R.sort()
H,W=H+1,W+1
for i in range(len(R)):
  if R[i][1]:
    P+=W*R[i][0]
    H-=1
  else:
    P+=H*R[i][0]
    W-=1
print(P)

Measured memory_bytes: 103824
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <map>
#include <set>
#include <cstdio>
#include <cmath>
#define rep(i,l,n) for(lint i=l;i<n;i++)
#define rer(i,l,n) for(lint i=l;i<=n;i++)
#define all(a) a.begin(),a.end()
#define o(a) cout<<a<<endl
#define pb(a) push_back(a)
#define mk(a,b) make_pair(a,b)
#define fi first
#define se second
using namespace std;
typedef long long lint;
typedef vector<int> vi;
typedef vector<lint> vli;
typedef vector<vi> vvi;
typedef pair<int,int> pii;

string change(int n){
	stringstream ss;
	ss<<n;
	return ss.str();
}

int main(){
	int n;
	string s;
	while(1){
		cin>>n;
		if(n==0) break;
		cin>>s;
		string t="";
		rep(i,0,n){
			int bef=s[0]-'0',suc=1;
			rep(j,1,s.size()){
				int now=s[j]-'0';
				if(now==bef){
					suc++;
				}else{
					t+=change(suc);
					t+='0'+bef;
					bef=now;
					suc=1;
				}if(j==s.size()-1){
					t+=change(suc);
					t+='0'+bef;
				}
			}
			if(s.size()==1){
				t+='1';
				t+=s[0];
			}
			s=t;
			t.clear();
		}
		o(s);
	}
}

Measured memory_bytes: 1364
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    private static java.util.Scanner scanner = new java.util.Scanner(System.in);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        List<Long> list = IntStream.range(0, n)
                .map(i -> scanner.nextInt())
                .boxed()
                .collect(Collectors.groupingBy(i -> i, Collectors.reducing(0, e -> 1, Integer::sum)))
                .entrySet().stream()
                .flatMapToLong(entry -> IntStream.range(0, entry.getValue() / 2).mapToLong(i -> entry.getKey()))
                .boxed()
                .sorted(Comparator.reverseOrder())
                .collect(Collectors.toList());

        System.out.println(list.size() < 2 ? 0 : list.get(0) * list.get(1));
    }
}

Measured memory_bytes: 69392
//****** @author mdazmat9 **********
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define UB upper_bound
#define LB lower_bound
#define BS binary_search
#define MP make_pair
#define EB emplace_back
#define endl "\n"
#define PI 3.1415926535897932384626433832795
#define MOD 1000000007
#define F first
#define S second
#define ALL(a) (a).begin(),(a).end()
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
ll maxdeg=0;
vector<ll> adj[100005];
map<pair<ll,ll>,ll> mp;
ll a[100005];

void solve() {
ll n;cin>>n;
for(ll i=0;i<n-1;i++){
    ll a,b;cin>>a>>b;
    a--;b--;
    mp[{min(a,b),max(a,b)}]=i+1;
    adj[a].EB(b);
    adj[b].EB(a);
}
 maxdeg=0;
ll index=0;
for(ll i=0;i<n;i++){
    if(adj[i].size()>maxdeg){
        maxdeg=adj[i].size();
    }
    if(adj[i].size()==1)index=i;
}
cout<<maxdeg<<endl;
bool visited[n];
memset(visited,false, sizeof(visited));
queue<pair<ll,ll> > q;
q.push({index,1});
while(!q.empty()){
    ll num=q.front().F;
    ll count=q.front().S;
    visited[num]=true;
    q.pop();
    for(auto x:adj[num]){
        if(!visited[x]){
            ll ans=mp[{min(num,x),max(num,x)}];
            a[ans]=count;
            count++;
            if(count==maxdeg+1)count=1;
            q.push({x,count});
        }
    }
}
for(ll i=1;i<n;i++){
    cout<<a[i]<<endl;
}

}
int main()
{
    IOS;
    ll t=1;
   //  cin>>t;
    while(t--){
        solve();
    }
    return 0;
}

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

int main() {
    int a,b;
    cin >> a >> b;
    int p=0;
    if(a>=13)p=b;
    else if(a>=6)p=b/2;
    cout << p << '\n';
}


Measured memory_bytes: 256
#include <iostream>
#include <vector>
#include <chrono>
#include <random>
#include <cassert>
#include <algorithm>

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

struct Edge {
	int u, v, c, id;
	void read() {
		std::cin >> u >> v;
		c = 1e9;
		u--;v--;
	}
};

int main() {
	std::ios_base::sync_with_stdio(false); std::cin.tie(NULL);
	int n, m;
	std::cin >> n >> m;
	std::vector<int> dist(n);
	for(int i = 0; i < n; i++) {
		std::cin >> dist[i];
	}
	std::vector<int> col(n, 0);
	std::vector<Edge> edges(m);
	int c = 0;
	for(auto &e : edges) {
		e.read();
		e.id = c++;
	}
	bool got = false;
	std::sort(edges.begin(), edges.end(), [&](Edge e1, Edge e2) { return std::min(dist[e1.u], dist[e1.v]) < std::min(dist[e2.u], dist[e2.v]); });
	for(auto &e : edges) {
		int u = e.u, v = e.v;
		if(col[u] && col[v]) continue;
		if(dist[u] != dist[v]) continue;
		if(!col[u] && !col[v]) {
			col[u] = -1;
			col[v] = 1;
		} else if (!col[u]) {
			col[u] = -col[v];
		} else {
			col[v] = -col[u];
		}
		e.c = dist[u];
		got = true;
	}
	if(!got) {
		std::cout << "-1\n";
		return 0;
	}
	for(auto &e : edges) {
		int u = e.u, v = e.v;
		if(col[u] && col[v]) continue;
		if(!col[u] && !col[v]) {
			continue;
		}
		if(!col[u] && dist[u] > dist[v]) {
			col[u] = col[v];
		} else if(!col[v] && dist[v] > dist[u]) {
			col[v] = col[u];
		} else {
			continue;
		}
		e.c = abs(dist[u] - dist[v]);
	}
	std::sort(edges.begin(), edges.end(), [&](Edge e1, Edge e2) { return e1.id < e2.id; });
	for(int i = 0; i < n; i++) {
		if(!col[i]) {
			std::cout << "-1\n";
			return 0;
		}
	}
	for(int i = 0; i < n; i++) {
		std::cout << char(col[i] == 1 ? 'W' : 'B');
	}
	std::cout << '\n';
	for(auto e : edges) {
		std::cout << e.c << '\n';
	}
}

Measured memory_bytes: 6400
#include<iostream>

using namespace std;

int main(){
  int a[3];

  for(int i=0;i<3;i++)
    cin >> a[i];

  int temp;

  for(int i=0;i<3;i++){
    for(int j=2;j>i;j--){
      if(a[j] < a[j-1]){
	temp = a[j];
	a[j] = a[j-1];
	a[j-1] = temp;
      }
    }
  }

  cout << a[0] << " " << a[1] << " " << a[2] << "\n";
}

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

int main() {
    string s; cin >> s;
    int flag = 1;
    for (int i = 0; i < 3; i++) if (s[i] == s[i+1]) flag = 0;
    string ans = flag ? "Good" : "Bad";
    cout << ans << endl;
}

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

int main() {
  int A, B, K;
  cin >> A >> B;
  if((A - B)%2 != 0){
    cout << "IMPOSSIBLE" << endl;
  }else
  if(A <= B){
    cout << (A + B)/2 << endl;
  }else
  if(A > B){
    cout << (A + B)/2 << endl;
  }
}  

Measured memory_bytes: 256
#!/usr/bin/env python3
from collections import defaultdict,deque
from heapq import heappush, heappop
from bisect import bisect_left, bisect_right
import sys, random, itertools, math
sys.setrecursionlimit(10**5)
input = sys.stdin.readline
sqrt = math.sqrt
def LI(): return list(map(int, input().split()))
def LF(): return list(map(float, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def II(): return int(input())
def IF(): return float(input())
def S(): return input().rstrip()
def LS(): return S().split()
def IR(n): return [II() for _ in range(n)]
def LIR(n): return [LI() for _ in range(n)]
def FR(n): return [IF() for _ in range(n)]
def LFR(n): return [LI() for _ in range(n)]
def LIR_(n): return [LI_() for _ in range(n)]
def SR(n): return [S() for _ in range(n)]
def LSR(n): return [LS() for _ in range(n)]
mod = 1000000007
inf = float("INF")

#solve
def solve():
    n, x, m = LI()
    if n <= 10 ** 5:
        ans = x
        for _ in range(n - 1):
            x = x ** 2 % m
            ans += x
        print(ans)
        return
    else:
        d = defaultdict(int)
        xd = x
        ans = 0
        for i in range(n + 1):
            if d[x]:
                break
            ans += x
            d[x] = (i + 1, ans)
            x = x ** 2 % m
        i += 1
        cycle = i - d[x][0]
        cycle_score = ans - d[x][1] + x
        n = n - d[x][0] + 1
        ans = d[x][1] - x
        diff = n % cycle
        tern = n // cycle
        ans += tern * cycle_score
        for j in range(diff):
            ans += x
            x = x ** 2 % m
        print(ans)
    return


#main
if __name__ == '__main__':
    solve()


Measured memory_bytes: 90484