akhauriyash/Code-Regression huggingface dataset:
from collections import Counter

class Unionfind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * (n+1)
        
    def find(self, x):
        if(self.parents[x] < 0):
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
        
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        
        if(x == y):
            return
        
        if(self.parents[x] > self.parents[y]):
            x, y = y, x
            
        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def size(self, x):
        return -self.parents[self.find(x)]
    
    def same(self, x, y):
        return self.find(x) == self.find(y)
    
    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]
    
    def group_count(self):
        return len(self.roots())
    
    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}
    
    def __str__(self):
        return '\n'.join('{}:{}'.format(r, self.members(r)) for r in self.roots())

N, K, L = map(int, input().split())

uf = Unionfind(N)
uf1 = Unionfind(N)

for _ in range(K):
    p, q = map(int, input().split())
    uf.union(p-1, q-1)
    
for _ in range(L):
    r, s = map(int, input().split())
    uf1.union(r-1, s-1)
    
pairs = [(uf.find(i), uf1.find(i)) for i in range(N)]
#print(pairs)
    
c = Counter(pairs)
#print(c)
ans = [c[pairs[i]] for i in range(N)]

print(*ans)

Measured memory_bytes: 46964
#include <bits/stdc++.h>
 using namespace std;
 int main() { 
   int N; cin >> N;  
      vector<int> A(N); 
   for (int i = 0; i < N; ++i) { 
     cin >> A[i]; 
     --A[i]; 
   } 
   vector<int> B(N); 
   for (int i = 0; i < N; ++i) { 
     cin >> B[i]; 
   } 
   vector<int> C(N-1); 
   for (int i = 0; i < N; ++i) { 
     cin >> C[i]; 
   } 
    int ans = 0; 
   for (int i = 0; i < N; ++i) { 
     ans += B[A[i]]; 
     if (i > 0 && A[i] == A[i-1]+1) { 
       ans += C[A[i-1]]; 
     } 
   } 
   cout << ans << endl; 
 }


Measured memory_bytes: 256
#!/usr/bin/python
# -*- coding: utf-8 -*-

s = raw_input()
H, W = [int(x) for x in s.split()]
# H, W = 500,500
A = [None] * H

for i in xrange(H):
	s = raw_input()
	A[i] = [int(x) for x in s.split()]
	# A[i] = [j for j in xrange(W)]

choose = [[False]*W for i in xrange(H)]
answer = -1
answerOps = []
ops = []

def dfs(y, x, even):
	global H, W, A, answer, answerOps, ops

	if x >= W:
		x, y = 0, y+1
	if x == 0 and y == H:
		if even > answer:
			answer = even
			answerOps = ops
		return
	if even + (H-y-1)*W + (W-x) <= answer:
		return

	# print y, x, A[y][x], even
	# print A

	coin = A[y][x]
	if coin % 2 == 1:
		A[y][x] = 0
		if x+1 < W:
			A[y][x+1] += coin
			ops.append((y, x, y, x+1))
			dfs(y, x+1, even+1)
			ops = ops[:-1]
			A[y][x+1] -= coin

		if y+1 < H:
			A[y+1][x] += coin
			ops.append((y, x, y+1, x))
			dfs(y, x+1, even+1)
			ops = ops[:-1]
			A[y+1][x] -= coin
		A[y][x] = coin

		dfs(y, x+1, even)
	else:
		dfs(y, x+1, even+1)


# dfs(0, 0, 0)


def check(y, x):
	if x+1 < W:
		if A[y][x+1] % 2 == 1:
			return 'right'
	if y+1 < H:
		if A[y+1][x] % 2 == 1:
			return 'down'
	if x+1 < W:
		return 'right'
	if y+1 < H:
		return 'down'

for i in xrange(H):
	for j in range(W):
		if A[i][j] % 2 == 1:
			ret = check(i, j)
			if ret == 'right':
				A[i][j+1] += A[i][j]
				answerOps.append((i, j, i, j+1))
			elif ret == 'down':
				A[i+1][j] += A[i][j]
				answerOps.append((i, j, i+1, j))

print len(answerOps)
for t in answerOps:
	print '%d %d %d %d' % tuple([x+1 for x in t])

Measured memory_bytes: 59036
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <set>

using namespace std;

int main() {
	int n, k;
	long ans;
	cin >> n >> k;
	ans = k;
	for (int i = 0; i < n - 1; i++) {
		ans *= k - 1;
	}
	cout << ans << endl;
	return 0;
}

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

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
#define REP(i, n) for(int i=0; i<n; i++)
#define REPi(i, a, b) for(int i=int(a); i<int(b); i++)
#define MEMS(a,b) memset(a,b,sizeof(a))
#define mp make_pair
template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }
const ll MOD = 1e9+7;

int main(){
    ll N;
    cin >> N;
    ll K;
    cin >> K;
    vector<ll> H(N);
    REP(i,N){
        cin >> H[i];
    }

    sort(H.rbegin(), H.rend());

    ll ans = 0;

    REPi(i,K,N){
        ans += H[i];
    }

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


Measured memory_bytes: 1792
#include <bits/stdc++.h>  // g++ -std=c++14 -o a a.cpp

using namespace std;

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

#define rep(i, n) for(int i = 0; i < (n); i++)
#define repto(i, n) for(int i = 0; i <= (n); i++)
#define all(c) (c).begin(), (c).end()
#define uniq(c) c.erase(unique(all(c)), (c).end())
#define _1 first
#define _2 second
#define pb push_back
#define INF 1145141919
#define MOD 1000000007
#define DEBUG(x) cout << #x << ": " << x << endl;

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

__attribute__((constructor)) void initial() {
    cin.tie(0);
    ios::sync_with_stdio(false);
}

int main() {
    int N;
    cin >> N;
    set<string> D;
    rep(i, N) {
        string cmd;
        string str;
        cin >> cmd >> str;

        if (cmd == "insert") {
            D.insert(str);
        }

        if (cmd == "find") {
            if (D.find(str) != D.end()) {
                cout << "yes" << endl;
            } else {
                cout << "no" << endl;
            }
        }
    }
}


Measured memory_bytes: 29028
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int N,x;
    scanf("%d",&N);
    x = (N % 1000);
    if(x>=1){printf("%d\n",(1000-x));}
    else if(x==0){printf("0\n");}
    else if(x<1){printf("%d\n",(1000-N));}
    return 0;
}


Measured memory_bytes: 1732
using System;
using System.Collections.Generic;

namespace ConsoleApp1
{

    class Program
    {

        static void Main(string[] args)
        {
            var input = Console.ReadLine().Split(' ');
            int n = int.Parse(input[0]);
            int m = int.Parse(input[1]);

            List<int>[] rooms = new List<int>[n + 1];
            var sign = new int[n + 1];

            for (int i = 0; i <= n; i++)
            {
                rooms[i] = new List<int> { };
            }

            for (int i = 0; i < m; i++)
            {
                var input1 = Console.ReadLine().Split(' ');
                int a = int.Parse(input1[0]);
                int b = int.Parse(input1[1]);
                rooms[a].Add(b);
                rooms[b].Add(a);
            }

            var q = new Queue<int> { };

            q.Enqueue(1);

            while (q.Count > 0)
            {
                int thisroom = q.Dequeue();
                foreach (int room in rooms[thisroom])
                {
                    if (sign[room] != 0) continue;
                    sign[room] = thisroom;
                    q.Enqueue(room);
                }
            }

            bool solved = true;

            for (int i = 2; i <= n; i++)
            {
                if (sign[i] == 0)
                    solved = false;
            }

            if (solved)
            {
                Console.WriteLine("Yes");
                for (int i = 2; i <= n; i++)
                    Console.WriteLine(sign[i]);
            }
            else
            {
                Console.WriteLine("No");
            }

        }


    }
}



Measured memory_bytes: 56096
package main

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

func main() {
	var wtr = bufio.NewWriter(os.Stdout)
	var scanner = bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanLines)
	A := [][]int{{0, 0, 0}, {0, 0, 0}, {0, 0, 0}}
	B := [][]bool{{false, false, false}, {false, false, false}, {false, false, false}}
	for i := 0; i < 3; i++ {
		if scanner.Scan() {
			str := scanner.Text()
			cols := strings.Split(str, " ")
			A[i][0], _ = strconv.Atoi(cols[0])
			A[i][1], _ = strconv.Atoi(cols[1])
			A[i][2], _ = strconv.Atoi(cols[2])
		}
	}
	var N int
	if scanner.Scan() {
		str := scanner.Text()
		N, _ = strconv.Atoi(str)
	}
	for r := 0; r < N; r++ {
		if scanner.Scan() {
			str := scanner.Text()
			a, _ := strconv.Atoi(str)
			for i := 0; i < 3; i++ {
				for j := 0; j < 3; j++ {
					if A[i][j] == a {
						B[i][j] = true
					}
				}
			}
		}
	}

	ans := "No"
	for p := 0; p < 3; p++ {
		if (B[p][0] && B[p][1] && B[p][2]) || (B[0][p] && B[1][p] && B[2][p]) {
			ans = "Yes"
			break
		}
	}
	if (B[0][0] && B[1][1] && B[2][2]) || (B[0][2] && B[1][1] && B[2][0]) {
		ans = "Yes"
	}

	fmt.Fprintln(wtr, ans)
	_ = wtr.Flush()
}


Measured memory_bytes: 640
#include <stdio.h>
#include <stdbool.h>

bool flag_rightangle(int a, int b, int c)//三辺a,b,cを持つ三角形が直角三角形かどうか
{
    if ((a * a == b * b + c * c) || (b * b == c * c + a * a) || (c * c == a * a + b * b)){
        return true;
    } else {
        return false;
    }
}

int main(void){
    int line_number;
    scanf("%d", &line_number);
    for(int i = 0; i < line_number; i++){
        int first_number;
        int second_number;
        int third_number;
        scanf("%d %d %d", &first_number, &second_number, &third_number);
        if (flag_rightangle(first_number, second_number, third_number) == true){
            printf("YES\n");
        } else {
            printf("NO\n");
        }
    }
    return 0;
}

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

int main(){
    int N, K;
    string S;
    cin >> N >> K;
    cin >> S;
    int result = 0;
    for(int i = 0; i < N - 1; i++){
        if(S[i] == S[i+1]) result++;
    }
    int ans = min(result + 2 * K, N - 1);
    cout << ans << endl;
}

Measured memory_bytes: 512
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <set>

using namespace std;

int l[2010];
int num[2010];


int main()
{
    int n;scanf("%d",&n);
    for (int i=0;i<n;++i)
        scanf("%d",&l[i]);
    for (int i=0;i<n;++i)
        ++num[l[i]];

    for (int i=1;i<=2001;++i)
        num[i]+=num[i-1];

    long long ans=0;
    for (int i=0;i<n;++i)
    for (int j=0;j<n;++j)
    {
        if (i==j) continue;
        int minn=l[i]-l[j];
        if (l[j]-l[i]>minn) minn=l[j]-l[i];
        int maxx=l[i]+l[j];
        int tmp=num[maxx-1]-num[minn];
        if (l[i]<maxx && l[i]>minn) --tmp;
        if (l[j]<maxx && l[j]>minn) --tmp;
        ans+=1LL*tmp;
    }
    printf("%lld\n",ans/6);
}


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

using namespace std;

map< int64_t, int > prime_factor(int64_t n) {
    map< int64_t, int > ret;
    for(int64_t i = 2; i * i <= n; i++) {
        while(n % i == 0) {
        ret[i]++;
        n /= i;
        }
    }
    if(n != 1) ret[n] = 1;
    return ret;
}


int main(void) {
    int N;
    cin >> N;
    int ans = INT32_MAX;
    for(int i=0; i<N; i++) {
        int A;
        cin >> A;
        auto prime = prime_factor(A);
        ans = min(ans, prime[2]);
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
#include<iostream>
#include<vector>
#include<cstdio>
#include<string>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<string.h>
#include <iomanip>
#include <sstream>
using namespace std;

int main() {
  string s;
  int ans = 0;

  cin >> s;

  //case1
  if(s[0] == 'A'){
    ans++;
//    cout << "case1: OK" << endl;
  }

  //case2
  int ccnt = 0;
  for(int i = 2; i < (s.size() - 1); i++){
    if(s[i] == 'C'){
      ccnt++;
    }
  }
  if(ccnt == 1){
    ans++;
//    cout << "case2: OK" << endl;
  }

  //case3
  int smllcnt = 0;
  for(int i = 0; i < s.size(); i++){
    if(s[i] >= 'a' && s[i] <= 'z'){
      smllcnt++;
    }
  }
  if(smllcnt == s.size()-2){
    ans++;
//    cout << "case3: OK" << endl;
  }

  if(ans == 3){
    cout << "AC" << endl;
  }else{
    cout << "WA" << endl;

  }
}


Measured memory_bytes: 256
#include <algorithm>  //min, max, sort, unique, fill
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>  //pair, swap,
#include <vector>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
using VI = vector<ll>;

#define FOR(i, a, b) for (ll i = (a); i < (b); i++)
#define REP(i, n) for (ll i = 0; i < (n); i++)

static const ll kIntMax = numeric_limits<ll>::infinity();
static const double kFloatMax = numeric_limits<double>::infinity();

vector<ll> vi;

int main() {
  ll a, b, c, x, y;
  cin >> a >> b >> c >> x >> y;
  ll price = 0, tmp;
  price = 1000000000;
  REP(i, 100001) {
    tmp = i * c * 2 + max(0ll, x - i) * a + max(0ll, y - i) * b;
    if (tmp < price) price = tmp;
    if (i > x && i > y) break;
  }

  /*  if (a + b < c * 2)
      price = a * x + b * y;
    else {
      if (c * 2 <= a) {
        price += x * c * 2;
        y -= x;
        x = 0;
        // cerr << "price:" << price << "x:" << x << "y:" << y << endl;
      }

      if (c * 2 <= b && y > 0) {
        price += y * c * 2;
        x -= y;
        y = 0;
        // cerr << "price:" << price << "x:" << x << "y:" << y << endl;
      }

      x = max(0ll, x);
      y = max(0ll, y);

      ll z = ((ll)min(x, y) / 2) * 2;
      price += z * c * 2 + (x - z) * a + (y - z) * b;
      // cerr << "price:" << price << "x:" << x << "y:" << y << "z:" << z <<
    endl;
    }
  */
  cout << price << endl;

  return 0;
}


Measured memory_bytes: 256
S = input()
ans = 0
if S[0] == '0':
    for i, x in enumerate(S):
        if i%2 == 0 and x == '1':
            ans +=1
        elif i%2 == 1 and x =='0':
            ans += 1
elif S[0] == '1':
    for i, x in enumerate(S):
        if i%2 == 0 and x == '0':
            ans +=1
        elif i%2 == 1 and x =='1':
            ans += 1
print(ans)

Measured memory_bytes: 3188
#include <stdio.h>
int a[10000];
int i,j;
int main(void) {
  for(i=0;i<10000;i++) {
    scanf("%d",&a[i]);
    if(a[i]==0) break;
  }
  for(j=0;j<i;j++) {
    printf("Case %d: %d\n",j+1,a[j]);
  }
return 0;
}

Measured memory_bytes: 632
#include<stdio.h>
#include<stdlib.h>

int main(void){
    int i, N, V, j, k;
    int *In;
    
    scanf("%d",&N);
    In = (int*)malloc(sizeof(int)*N);
      for(k=0 ; k<N ; k++){
            scanf("%d",&In[k]);
        }
  printf("%d",In[0]);
             for(k=1 ; k<N ; k++){
            printf(" %d",In[k]);
        }
        printf("\n");
  
    
    for(i=1 ; i<N ; i++){
        V=In[i];
        j=i-1;
        while(j>=0 && In[j]>V){
            In[j+1] = In[j];
            j--;
            In[j+1]=V;
        }
        printf("%d",In[0]);
        for(k=1 ; k<N ; k++){
            printf(" %d",In[k]);
        }
        printf("\n");
    }
    
    return 0;
}


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

const int MAX_N = 25;
int N;
int ROOT_ID;

typedef struct {
  int parent, left, right;
} node;

node nodes[MAX_N];

void preorder(int id) {
  if (id == -1) return;

  cout << ' ' << id;
  preorder(nodes[id].left);
  preorder(nodes[id].right);
}

void inorder(int id) {
  if (id == -1) return;

  inorder(nodes[id].left);
  cout << ' ' << id;
  inorder(nodes[id].right);
}

void postorder(int id) {
  if (id == -1) return;
    
  postorder(nodes[id].left);
  postorder(nodes[id].right);
  cout << ' ' << id;
}

void solve() {
  cout << "Preorder" << endl;
  preorder(ROOT_ID);
  cout << endl;

  cout << "Inorder" << endl;
  inorder(ROOT_ID);
  cout << endl;

  cout << "Postorder" << endl;
  postorder(ROOT_ID);
  cout << endl;  
}

int main() {
  for (int i = 0; i < MAX_N; i++) {
    node n;
    n.parent = n.left = n.right = -1;
    nodes[i] = n;
  }

  cin >> N;
  for (int i = 0; i < N; i++) {
    int id, l, r;
    cin >> id >> l >> r;
    nodes[id].left = l;
    nodes[id].right = r;
    nodes[l].parent = nodes[r].parent = id;
  }

  for (int i = 0; i < N; i ++) {
    if (nodes[i].parent == -1) {
      ROOT_ID = i;
      break;
    }
  }

  solve();

  return 0;
}

Measured memory_bytes: 1160
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int mod=1000000007;
int dp[3030][3030];
int r[3030],cnt[3030];
char s[3030];
int main()
{
	int n,m,l1,r1;
	scanf("%d%d",&n,&m);
	scanf("%s",s+1);
	memset(cnt,0,sizeof(cnt));
	for(int i=1;i<=n;i++)
		cnt[i]=s[i]-'0';
	for(int i=1;i<=n;i++)
		cnt[i]+=cnt[i-1];
	for(int i=1;i<=n;i++)
		r[i]=i;
	for(int i=1;i<=m;i++)
	{
		scanf("%d%d",&l1,&r1);
		r[l1]=max(r[l1],r1);
	}
	for(int i=1;i<=n;i++)
		r[i]=max(r[i],r[i-1]);
	memset(dp,0,sizeof(dp));
	dp[1][0]=1;
	for(int i=1;i<=n;i++)
		for(int j=0;j<i;j++)
			if(dp[i][j])
			{
				if(cnt[r[i]]!=j)
					(dp[i+1][j+1]+=dp[i][j])%=mod;
				if(i-1-j!=r[i]-cnt[r[i]])
					(dp[i+1][j]+=dp[i][j])%=mod;
			}
	printf("%d",dp[n+1][cnt[n]]);
	return 0;
}

Measured memory_bytes: 36096
# include <iostream>
using namespace std;
int main()
{
	int n,m,a,b;
	a=0; 
	b=0;
	cin>>n>>m;
	if(n>=2)
	{
		a=n*(n-1)/2;
	}
	if(m>=2)
	{
		b=m*(m-1)/2;
	}
	cout<<a+b;
}

Measured memory_bytes: 3576
import std.stdio, std.algorithm, std.conv, std.array, std.string, std.math, std.typecons, std.numeric;

void main()
{
    auto nm = readln.split.to!(int[]);
    auto N = nm[0];
    auto M = nm[1];
    auto qs = new int[](N);
    foreach (_; 0..M) {
        auto ab = readln.split.to!(int[]);
        ++qs[ab[0]-1];
        ++qs[ab[1]-1];
    }
    foreach (q; qs) {
        if (q%2 == 1) {
            writeln("NO");
            return;
        }
    }
    writeln("YES");
}

Measured memory_bytes: 3708
import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int n = sc.nextInt();
        Integer[] p = new Integer[n];
        for (int i=0; i<n; i++) {
            p[i] = sc.nextInt() - x;
        }
        Arrays.sort(p, (a, b) -> {
            int sub = Math.abs(a) - Math.abs(b);
            return sub == 0 ? a : sub;
        });
        int sub = 0;
        if (n != 0) {
            if (p[0] == 0) {
                sub--;
                for (int i=1; i<n; i=i+2) {
                    if (p[i] != sub) {
                        break;
                    }
                    if (i+1 >= n || p[i+1] != -1 * sub){
                        sub = -1 * sub;
                        break;
                    }
                    sub--;
                }
            }
        }
        System.out.println(x + sub);
    }
}

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

bool is_prime(int n)
{

    if(n==2)
        return true;
    if(n%2==0)
        return false;
    for(int i=3;i<=sqrt(n);i+=2)
    {
        if(n%i==0)
            return false;
    }
    return true;
}
#define ll long long
#define loop(n) for(int i=0;i<n;i++)

int main()
{
    int n;
    cin>>n;
    double a[n],x=0.0;
    loop(n)cin>>a[i],x+=(1/a[i]);
    x=1/x;
    cout<<fixed<<setprecision(7)<<x;
}



Measured memory_bytes: 256
N,C = map(int,input().split())
src = [tuple(map(int,input().split())) for i in range(N)]

cumsumr = [0]
cummaxr = [0]
cummaxr2 = [0]
px = 0
for x,v in src:
    cumsumr.append(cumsumr[-1] + v-(x-px))
    cummaxr.append(max(cummaxr[-1], cumsumr[-1]))
    cummaxr2.append(max(cummaxr2[-1], cumsumr[-1]-x))
    px = x

cumsuml = [0]
cummaxl = [0]
cummaxl2 = [0]
px = C
for x,v in src[::-1]:
    cumsuml.append(cumsuml[-1] + v-(px-x))
    cummaxl.append(max(cummaxl[-1], cumsuml[-1]))
    cummaxl2.append(max(cummaxl2[-1], cumsuml[-1]-(C-x)))
    px = x

ans = max(cummaxr[-1], cummaxl[-1])
for i in range(N):
    ans = max(ans, cummaxr2[i] + cummaxl[N-i])
    ans = max(ans, cummaxl2[i] + cummaxr[N-i])
print(ans)

Measured memory_bytes: 32704
#include <bits/stdc++.h>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<string.h>
using namespace std;
#define pb push_back
#define all(v) v. begin(),v. end()
#define  rep(i,n,v) for(i=n;i<v;i++)
#define per(i,n,v) for(i=n;i>v;i--)
#define ff first 
#define ss second 
#define pp pair<ll,ll>
#define ll  long long
#define endl '\n'
void solve()
{
  ll n, a,m=0,b=1, c,k=0, i, j,l=1e9+7;
  string s, r, y;
  cin>>n;
  ll ar[n];
  rep(i,0,n) {cin>>ar[i];k+=ar[i];k%=l;}
  rep(i,0,n)
  {
    k-=ar[i];
    if(k<0) k+=l;
    m+=(ar[i]*k);
    m%=l;
  }
  cout<<m<<endl;
}
int main()
{
 ios_base::sync_with_stdio(false);
  cin. tie(0);cout. tie(0);
    ll t=1;
   //cin>>t;
    while(t--)
    {
      solve();
    }
    return 0;
}

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

int main() {
	// your code goes here
	char s[101];
	cin.getline(s,101);
/*	char s1[100];
	cin.getline(s, 100); 
	strcpy(s1,s);
	reverse(s1, s1 + strlen(s1));*/
	int count = 0;
	int n = strlen(s);
	for(int i = 0; i<n; i++)
	{
		if(s[i]!=s[n-i-1])
		{
			count++;
		}
	}
	cout<<count/2;
	return 0;
}

Measured memory_bytes: 3616
#include <stdio.h>

int main(void)
{
	int n, i, array[10], f;
	
	while (scanf("%d", &n), n != -1){
		for (i = 0; i < 10; i++){
			array[i] = 0;
		}
		
		i = 0;
		while (n != 0){
			array[i] = n % 4;
			n /= 4;
			i++;
		}
		
		f = 0;
		for (i = 9; i >= 0; i--){
			if (f == 0 && array[i] != 0){
				f = 1;
			}
			if (f || !i){
				printf("%d", array[i]);
			}
		}
		puts("");
	}
	
	return (0);
}

Measured memory_bytes: 612
// inputに入力データ全体が入る
function Main(input) {
	input = input.split("\n"); // 1行目がinput[0], 2行目がinput[1], …に入る
    // ここに処理を書く
    var r = input[0]
    
    var ans = 3 * r * r
	// console.logは標準出力に1行出力します (自動的に最後に改行が入ります)
	console.log(ans);
}

// ※この行以降は編集しない (標準入力から一度に読み込みMainを呼び出します)
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


Measured memory_bytes: 21064
package main

import (
	"fmt"
	"strings"
)

func main() {
	var str string

	fmt.Scan(&str)

	flag := true
	flag = flag && (strings.Count(str[2:len(str)-1], "C") == 1)

	idx := strings.Index(str[2:len(str)-1], "C")

	flag = flag && (str[0] == 'A')
	flag = flag && (idx != -1)

	for i := range str {
		if i == 0 || i == idx+2 {
			continue
		}

		if str[i:i+1] != strings.ToLower(str[i:i+1]) {
			flag = false
		}
	}

	if flag {
		fmt.Println("AC")
	} else {
		fmt.Println("WA")
	}
}


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

int main(void)
{
	int n, x;
	while (true){
		cin >> n >> x;
		if (n==0 && x==0) break;
		
		int c = 0;
		for (int i=1; i<n-1; i++)
			for (int j=i+1; j<n; j++)
				for (int k=j+1; k<n+1; k++){
					int s = i+j+k;
					if (s==x) c++;
					else if (s>x) break;
				}
		cout << c << endl;
	}
	return 0;
}

Measured memory_bytes: 1160
#include <bits/stdc++.h>
using namespace std;
#define ALL(x) x.begin(),x.end()
//map<key,value>


int main(){
  int n;
  long long int fi=0,se=0,save=0;
  cin >> n;
  vector<int> a(n,0);
  for(int i=0;i<n;i++)cin >> a[i];
  sort(a.begin(),a.end());
  for(int i=n-1;i>=1;i--){
    if(a[i]==a[i-1]){
        fi = a[i];save = i;break;
    }
  }
  for(int i=n-1;i>=1;i--){
    if(a[i]==a[i-1] && a[i]<=fi && i <=save-2){
        se = a[i];break;
    }
  }
  cout << fi*se;
}


Measured memory_bytes: 640
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Math;
using MethodImplAttribute = System.Runtime.CompilerServices.MethodImplAttribute;
using MethodImplOptions = System.Runtime.CompilerServices.MethodImplOptions;

public static class P
{
    public static void Main()
    {
        var abm = Console.ReadLine().Split().Select(int.Parse).ToArray();
        var a = Console.ReadLine().Split().Select(int.Parse).ToArray();
        var b = Console.ReadLine().Split().Select(int.Parse).ToArray();

        var min = Enumerable.Repeat(0, abm[2]).Select(_ => Console.ReadLine().Split().Select(int.Parse).ToArray()).Min(x => a[x[0] - 1] + b[x[1] - 1] - x[2]);
        Console.WriteLine(Min(a.Min() + b.Min(), min));
    }
}


Measured memory_bytes: 37724
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define REP(i,n) for(int i=0; i<(n); i++)
#define REP2(i,x,n) for(int i=x; i<(n); i++)
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; }
int main()
{
	int N, T;
	cin >> N>>T;
	vector<int> t(N);
	REP(i, N) cin >> t[i];

	int t_end = 0;
	int cnt_t = 0;
	REP(i, N){
		if(t_end<=t[i]){
			cnt_t+=T;
		}
		else{
			cnt_t += t[i] + T - t_end;
		}
		t_end = t[i] +T;
	}
	cout << cnt_t << endl;
	cnt_t = 0;

	return 0;
}

Measured memory_bytes: 1024
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int> Pii;
typedef pair<ll,ll> Pll;
#define rep(i,n) for (ll i=0;i<n;++i)
#define rep2(i,a,b) for (ll i=a;i<b;++i)
const ll MOD=1000000007;
const ll INF=1e9;
const ll IINF=1e18;
const double EPS=1e-8;
const double pi=acos(-1);

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

int main(){
    string S;
    cin >> S;
    ll N=S.size();
    vector<ll> a(N+1,-1);
    bool alll=true,allr=true;
    rep(i,N){
        if (S[i]=='<') allr=false;
        if (S[i]=='>') alll=false;
    }
    if (allr||alll){
        cout << N*(N+1)/2 << endl;
        return 0;
    }
    rep(i,N){
        if (S[i]=='>'&&S[i+1]=='<'){
            a[i+1]=0;
        }
    }
    a[0]=0,a[N]=0;
    rep(i,N){
        if (S[i]=='<'){
            chmax(a[i+1],a[i]+1);
        }
    }
    rep(i,N){
        if (S[N-1-i]=='>'){
            chmax(a[N-1-i],a[N-i]+1);
        }
    }
    ll sum=0;
    rep(i,N+1){
        sum+=a[i];
    }
    cout << sum << endl;
}

Measured memory_bytes: 4740
# frozen_string_literal: true

def sum_distance(attributes = {})
  n = attributes[:N]
  m = attributes[:M]
  points = attributes[:points]

  points.sort!

  distances = []

  if m == 1
    puts 0
    exit
  end

  (0..m - 2).each do |t|
    length = (points[t] - points[t + 1]).abs
    distances.push(length)
  end

  distances.sort!

  (n - 1).times.each do
    distances.pop
  end

  distance_counter = 0
  distances.each do |num|
    distance_counter += num
  end

  distance_counter
end
n, m = gets.chomp.split.map(&:to_i)
points = gets.chomp.split.map(&:to_i)
puts sum_distance(points: points, N: n, M: m)


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

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

#define fr first
#define sc second
#define chmax(a,b) a=max(a,b)
#define chmin(a,b) a=min(a,b)
#define mp1(a,b,c) P1(a,P(b,c))

int RET=0;

vector<P1> f(const vector<P> &vec,int W,int H){
	//sort(vec.begin(),vec.end());
	vector<P1> ret;
	set<int> S;
	S.insert(0);
	S.insert(H);
	for(P p: vec){
		auto itr=S.lower_bound(p.sc);
		int x=*itr; int y=*--itr;
		ret.push_back(mp1(y,x,p.fr));
		S.insert(p.sc);
	}
	auto itr=S.begin();
	while(1){
		int x=*itr;
		itr++;
		if(itr==S.end())break;
		int y=*itr;
		ret.push_back(mp1(x,y,W));
	}
	sort(ret.begin(),ret.end());
	return ret;
}

int solve(int W,int H,int N,vector<P> p){
	if(RET>=2*(W+H))return 0;
	if(N==0)return 2*(W+H);
	vector<P> L,R;
	int m;
	if(1){
		/*vector<int> X;
		for(int i=0;i<N;i++){
			X.push_back(p[i].fr);
		}
		sort(X.begin(),X.end());
		X.erase(unique(X.begin(),X.end()),X.end());*/
		if(p[0].fr==p[N-1].fr){
			int ret=0;
			vector<int> Y;
			Y.push_back(0);
			Y.push_back(H);
			for(int i=0;i<N;i++){
				Y.push_back(p[i].sc);
			}
			sort(Y.begin(),Y.end());
			for(int i=0;i+1<Y.size();i++){
				chmax(ret,Y[i+1]-Y[i]);
			}
			chmax(RET,max(2*(H+max(W-p[0].fr,p[0].fr)),2*(ret+W)));
			return max(2*(H+max(W-p[0].fr,p[0].fr)),2*(ret+W));
		}
		//m=X[(X.size()-1)/2];
		//m=p[(p.size()-1)/2].fr;
		m=W/2;
		for(int i=0;i<N;i++){
			if(p[i].fr<=m){
				p[i].fr=m-p[i].fr;
				L.push_back(p[i]);
			}
			else {
				p[i].fr-=m+1;
				R.push_back(p[i]);
			}
		}
	}
	reverse(L.begin(),L.end());
	int ret=0;
	vector<P1> vec[2]={f(L,m,H),f(R,W-m-1,H)};
	map<int,int> M[2];
	int k[2]={};
	while(k[0]<vec[0].size()||k[1]<vec[1].size()){
		int t;
		if(k[0]==vec[0].size())t=1;
		else if(k[1]==vec[1].size())t=0;
		else if(vec[0][k[0]].fr<=vec[1][k[1]].fr)t=0;
		else t=1;
		P1 pp=vec[t][k[t]]; k[t]++;
		auto itr=M[1-t].lower_bound(pp.sc.fr);
		if(itr!=M[1-t].end()){
			chmax(ret,2*((pp.sc.fr-pp.fr)+itr->sc+pp.sc.sc)+2);
		}
		if(itr!=M[1-t].begin()){
			--itr;
			chmax(ret,2*((itr->fr-pp.fr)+itr->sc+pp.sc.sc)+2);
		}
		itr=M[t].lower_bound(pp.sc.fr);
		while(itr!=M[t].end()&&itr->fr+itr->sc<=pp.sc.fr+pp.sc.sc)M[t].erase(itr++);
		bool ok=itr==M[t].begin();
		if(!ok){
			--itr;
			ok=itr->fr+itr->sc<pp.sc.fr+pp.sc.sc;
		}
		if(ok)M[t].insert(pp.sc);
	}
	chmax(RET,ret);
	//chmax(ret,solve(m,H,L.size(),L));
	//chmax(ret,solve(W-m-1,H,R.size(),R));
	return ret;
}

int main(){
	int w,h,n;
	vector<P> vec;
	scanf("%d%d%d",&w,&h,&n);
	for(int i=0;i<n;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		vec.push_back(P(a,b));
	}
	sort(vec.begin(),vec.end());
	for(int i=0;i+1<vec.size();i++){
		chmax(RET,2*(h+vec[i+1].fr-vec[i].fr));
	}
	solve(w,h,n,vec);
	for(int i=0;i<n;i++){
		swap(vec[i].fr,vec[i].sc);
	}
	sort(vec.begin(),vec.end());
	for(int i=0;i+1<vec.size();i++){
		chmax(RET,2*(w+vec[i+1].fr-vec[i].fr));
	}
	solve(h,w,n,vec);
	cout<<RET<<endl;
	return 0;
	/*w=h=100000000;
	n=10000;
	for(int i=0;i<n;i++){
		int a=rand()%(w+1);
		int b=rand()%(w+1);
		vec.push_back(P(a,b));
	}*/
	sort(vec.begin(),vec.end());
	cout<<solve(w,h,n,vec)<<endl;
}


Measured memory_bytes: 35304
#include<iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<limits>
#include<iomanip>
#include<cmath>
#include<climits>

using namespace std;

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

const int mod=1e9+7;

int main(){
    int n;
    cin >> n;
    vector<int> h(n);
    for(int i=0;i<n;i++)    cin >> h[i];
    int ans=0;
    for(int i=0;i<n;i++){
        bool ok=true;
        for(int j=0;j<=i;j++){
            if(h[j]>h[i])   ok=false;
        }
        if(ok)  ans++;
    }
    cout << ans << endl;
    return 0;
}


Measured memory_bytes: 256
# coding: utf-8

INF = 10001
W, H, N = list(map(int, input().split(' ')))
cities = [list(map(int, input().split(' '))) for i in range(N)]

ways = 0
city = 1
while city < N:
    sx, sy = cities[city-1]
    gx, gy = cities[city]
    distx, disty = gx-sx, gy-sy
    if distx * disty > 0:
        tmp = min(abs(disty), abs(distx))
        ways += tmp
        distx -= tmp * int(distx/abs(distx))
        disty -= tmp * int(disty/abs(disty))
    ways += abs(distx) + abs(disty)
    city += 1
print(ways)


Measured memory_bytes: 5724
#include <iostream>
#include <numeric>
#include <vector>
#include <cmath>
#include <string>
#include <algorithm>
#include <set>
#include <map>
#include <queue>
#include <iomanip>
using namespace std;
using ll=long long;
using pll=pair<ll,ll>;
const ll MOD=1000000007;
const ll LINF=0x1fffffffffffffff;
const int INF=0x3fffffff;
const vector<pll> dir={{0,1},{1,0},{-1,0},{0,-1},{1,1},{-1,1},{1,-1},{-1,-1}};
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define rrep(i,a,b) for(ll i=b-1;i>=a;i--)
#define range(i) (i).begin(),(i).end()
#define rrange(i) (i).rbegin(),(i).rend()
inline ll gcd(ll a, ll b) { return b ? gcd(b, a % b) : a; }
inline ll lcm (ll a,ll b) {return a*b/gcd(a,b);}
inline constexpr int intpow(ll a,ll b){
    if(b==0) return 1;
    ll ans=intpow(a,b/2);
    return ans*ans%MOD*(b&1?a:1)%MOD;
}
inline constexpr int modf(ll n){
    ll ans=1;
    rep(i,0,n) {ans=ans*(n-i)%MOD;}
    return ans;
}

vector<ll> func,inv;
void init(ll n){
    func.resize(n+1);inv.resize(n+1);
    func[0]=1;
    rep(i,0,n) {func[i+1]=func[i]*(i+1)%MOD;}
    inv[n]=intpow(func[n],MOD-2);
    rrep(i,1,n+1) {inv[i-1]=inv[i]*i%MOD;}
}
ll comb(ll a,ll b) {return func[a]*inv[b]%MOD*inv[a-b]%MOD;}

inline long double median(vector<ll> v){
    ll size=v.size();
    sort(v.begin(),v.end());
    if (size % 2 == 1) return v[(size - 1) / 2];
    else return v[(size / 2) - 1] ;
}
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<class T,class L>ostream& operator << (ostream& os, pair<T,L>& p){os << p.first << " " << p.second;return os;}

int main(){
    ll x,y,z;
    cin>>x>>y>>z;
    cout<<(x+y)/(y+z)-1<<endl;
}

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

int main(){
  string S;
  ll K;
  cin >> S >> K;
  for(ll i=0;i<S.size();i++){
    if(S[i]=='1' and i+1!=K) continue;
    if(S[i]=='1' and i+1==K) { cout << S[i] << endl; return 0;};
    if(S[i]!='1'){ cout << S[i] << endl; return 0;}
  }
  return 0;
}


Measured memory_bytes: 256
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

 
public class Main {
 
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		int M = sc.nextInt();
		int[] ans = new int [N];
		HashMap<Integer, Integer> map = new HashMap<>();

		for(int i = 0; i < M; i++) {
			int keta = sc.nextInt();
			int num = sc.nextInt();
			//　同じ桁に違う数がある場合
			if(map.containsKey(keta)) {
				if(map.get(keta) != num) {
					System.out.print(-1);
					return;
				}
			}else {
				map.put(keta, num);
			}
		}

		//　最大桁数がない場合は1を補完
		if(N != 1) {
			if(!map.containsKey(1)) {
				map.put(1, 1);
			}
		}

		//　最大桁数が0の場合
		if(N != 1) {
			if(map.get(1) == 0) {
				System.out.print(-1);
				return;
			}
		}
		
		//　最少値を取得
		for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
			ans[entry.getKey() - 1] = entry.getValue();
		}

		for(int i = 0; i < N; i++) {
			System.out.print(ans[i]);
		}
		sc.close();
	}
	
}

Measured memory_bytes: 25300
import java.util.*;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int N = sc.nextInt();
		
		for (int i = 0; i < 26; i++) {
			for (int j = 0; j < 16; j++) {
				if ((i * 4) + (j * 7) == N) {
					System.out.println("Yes");
					return;
				}
			}
		}
		
		System.out.println("No");
	}
}

Measured memory_bytes: 21844
n = gets.split.map(&:to_i)
switch = Array.new(n[1]).map{Array.new(n[0],0)}
for i in 0..n[1]-1
  inst = gets.split.map(&:to_i)
  for j in 1..inst.length-1
    switch[i][inst[j]-1] = 1
  end
end
count = gets.split.map(&:to_i)
check = Array.new(n[0],0)
ans = 0
for i in 1..2**n[0]
  ok = 0
  for j in 0..n[1]-1
    result = 0
    for k in 0..n[0]-1
      result += 1 if switch[j][k] == 1 && check[k] == 1
    end
    ok += 1 if result % 2 == count[j]
  end
  ans += 1 if ok == n[1]
  check[0] += 1
  for j in 0..n[0]-2
    if check[j] == 2
      check[j] = 0
      check[j+1] += 1
    end
  end
end
puts ans


Measured memory_bytes: 1788
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        while(true) {
        	String cards = sc.nextLine();
        	if(cards.equals("-")) {
        		break;
        	}

            int count = Integer.parseInt(sc.nextLine());;
            for(int i = 0; i < count; i++) {
            	int shuffleNum = Integer.parseInt(sc.nextLine());
            	cards = cards.substring(shuffleNum) + cards.substring(0, shuffleNum);
            }
            System.out.println(cards);
        }
    }
}


Measured memory_bytes: 26420
# -*- coding: utf-8 -*-
import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue


class Scanner():
    @staticmethod
    def int():
        return int(sys.stdin.readline().rstrip())

    @staticmethod
    def string():
        return sys.stdin.readline().rstrip()

    @staticmethod
    def map_int():
        return [int(x) for x in Scanner.string().split()]

    @staticmethod
    def string_list(n):
        return [input() for i in range(n)]

    @staticmethod
    def int_list_list(n):
        return [Scanner.map_int() for i in range(n)]

    @staticmethod
    def int_cols_list(n):
        return [int(input()) for i in range(n)]


class Math():
    @staticmethod
    def gcd(a, b):
        if b == 0:
            return a
        return Math.gcd(b, a % b)

    @staticmethod
    def lcm(a, b):
        return (a * b) // Math.gcd(a, b)

    @staticmethod
    def divisor(n):
        res = []
        i = 1
        for i in range(1, int(n ** 0.5) + 1):
            if n % i == 0:
                res.append(i)
                if i != n // i:
                    res.append(n // i)
        return res

    @staticmethod
    def round_up(a, b):
        return -(-a // b)

    @staticmethod
    def is_prime(n):
        if n < 2:
            return False
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        d = int(n ** 0.5) + 1
        for i in range(3, d + 1, 2):
            if n % i == 0:
                return False
        return True


class PriorityQueue:
    def __init__(self, l=[]):
        self.q = l
        heapq.heapify(self.q)
        return

    def push(self, n):
        heapq.heappush(self.q, n)
        return

    def pop(self):
        return heapq.heappop(self.q)


MOD = int(1e09) + 7
INF = int(1e15)


def main():
    # sys.stdin = open("sample.txt")
    N = Scanner.int()
    ok = N + 1
    ng = 0
    while abs(ok - ng) > 1:
        m = (ok + ng) // 2
        if m * (m + 1) // 2 >= N:
            ok = m
        else:
            ng = m
    for i in reversed(range(1, ok + 1)):
        if N >= i:
            print(i)
            N -= i


if __name__ == "__main__":
    main()


Measured memory_bytes: 42988
#include <iostream>

using namespace std;

int main()
{
	 int N;
	 unsigned long long int sum = 0;
	cin >> N;

	for(int i=0; i<=N; i++){
		if(i % 3 == 0 && i % 5 == 0){
		}else if(i % 3 == 0){
		}else if(i % 5 == 0){
		}else {
			sum += i;
		}
	}
	cout << sum << "\n";
}


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

using namespace std;
 
const long long inf = 1e18;
#define ll long long
#define fr(i,a,n) for (int i=a;i<n;i++)
#define rfr(i,n,a) for (int i=n;i>=a;i--)
#define mp make_pair
#define pb push_back
#define pii pair<int,int>
#define pll pair<ll,ll> 
#define endl "\n"
typedef vector<int> VI;
typedef vector<ll> VL;

ll n,m,k;
bool snk[101];
int main() {
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	cin >> n >> k;
	fr(i,0,k) {
		cin >> m;
		fr(j,0,m) {
			int x;
			cin >> x;
			snk[x] = 1;
		}
	}
	int cnt = 0;
	fr(i,1,n+1)
		cnt += (!snk[i]);
	cout << cnt << endl;
	return 0;
}


Measured memory_bytes: 3648
#include<bits/stdc++.h>
using namespace std;
int main()
{
    string s;
    cin>>s;
    if(s=="SAT")
        cout<<1;
    else if(s=="SUN")
        cout<<7;
    else if(s=="MON")
        cout<<6;
    else if(s=="TUE")
        cout<<5;
    else if(s=="WED")
        cout<<4;
    else if(s=="THU")
        cout<<3;
    else
        cout<<2;
    }


Measured memory_bytes: 3604
#include <iostream>
#include <sstream>
#include <stack>
#include <iomanip>
#include <numeric>
#include <string>
#include <cstring>
#include <algorithm>
#include <functional>
#include <cstdlib>
#include <cassert>
#include <map>
#include <set>
#include <vector>
#include <utility>
#include <queue>
#include <cmath>

#define BEGIN(x) x.begin()
#define END(x) x.end()
#define ALL(x) BEGIN(x), END(x)
#define PAIR make_pair
#define VEC(type) vector<type >
#define endl '\n'
#define FIR first
#define SEC second
#define PB push_back
#define SZ(x) ((int)x.size())

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

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

using namespace std;

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

template<class U, class V>
istream& operator >>(istream& in, pair<U, V>& pr) {
    return in >> pr.first >> pr.second;
}

template<class U, class V>
ostream& operator <<(ostream& out, pair<U, V>& p) {
    return out << p.first << " " << p.second;
}

template<class T>
ostream& operator <<(ostream& out, vector<T> vec) {
    for (T& e : vec)
        out << e << " ";
    return out << endl;
}

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

bool winning[205][205];

void brute_force()
{
    FOR(s, 0, 209) {
        FOR(x, 0, s + 1) {
            int y = s - x;
            winning[x][y] = false;
            for (int i = 1;i <= x / 2; i++)
                if (!winning[x - 2 * i][y + i])
                    winning[x][y] = true;
            for (int i = 1;i <= y / 2; i++)
                if (!winning[x + i][y - 2 * i])
                    winning[x][y] = true;
        }
    }

    FOR(x, 0, 105) {
        cout << x << " : ";
        FOR(y, 0, 105) {
            if (!winning[x][y])
                cout << y << " ";
        }
        cout << endl;
    }
};

void solveSingleCase(int caseNo)
{
    lint X, Y;
    cin >> X >> Y;

    // brute_force();
    cout << (abs(X - Y) <= 1 ? "Brown" : "Alice") << endl;
};

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

    // Actual program code starts here.
    int T = 1;
    // cin >> T;
    FOR(tcase, 1, T + 1) {
        solveSingleCase(tcase);
    }
    return 0;
};


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

using namespace std;
typedef long long LL;
typedef pair<int,int> pii;

#define pb push_back
#define eb emplace_back
#define mp make_pair
#define fi first
#define se second

#ifdef OJ
#define debug(x)  do{cerr<<#x<<": "<<x<<"\n";}while(0)
#define debugv(x) do{cerr<<#x<<": ";for(auto&e: (x))cerr<<e<<" ";cerr<<"\n";}while(0)
#else
#define debug(x)
#define debugv(x)
#endif

#define all(x) (x).begin(), (x).end()
#define rsort(x) sort((x).rbegin(), (x).rend())
#define sz(x) ((int)x.size())
#define fori(i, n) for (int i = 0; i < (int)(n); ++i)
#define ford(i, n, e) for (int i = (int)(n); i >= (int)(e); --i)
#define fore(i, a, b) for (int i = (int)(a); i <= (int)(b); ++i)
template<typename T> bool mmax(T &m, const T q) { if (m < q) {m = q; return true;} else return false; }
template<typename T> bool mmin(T &m, const T q) { if (m > q) {m = q; return true;} else return false; }
#define RETURN(x) do{cout << (x) << '\n'; return 0;}while(0)

const int MOD = 1e9+7;
const int MAXN = 2e5+3;
const int INF = 1e9;

void solve() {
    int n; cin >> n;
    vector<int> c(1e5+1);
    LL sum = 0;
    fori(i,n) {
        int a; cin >> a;
        c[a]++;
        sum += a;
    }
    int q; cin >> q;
    while(q--) {
        int a,b; cin >> a >> b;
        sum -= (LL)c[a]*a;
        sum += (LL)c[a]*b;
        c[b] += c[a];
        c[a] = 0;
        cout << sum << '\n';
    }
}

int main(int argc, char **argv) {
#ifdef OJ
    freopen("input.txt", "rt", stdin);
    //freopen("output.txt", "wt", stdout);
#endif
    ios::sync_with_stdio(false);
    cin.tie(0);

    int ntest = 1; 
    //cin >> ntest; 
    while(ntest--) solve();

    return 0;
}


Measured memory_bytes: 3696
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
#include <map>
#include <set>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <queue>
#include <stack>

using namespace std;

#define REP(i, n) for(int i = 0;i < n;i++)
#define REPR(i, n) for(int i = n;i >= 0;i--)
#define FOR(i, m, n) for(int i = m;i < n;i++)
#define FORR(i, m, n) for(int i = m;i >= n;i--)
#define REPO(i, n) for(int i = 1;i <= n;i++)
#define ll long long
#define INF 1999999999
#define MINF -1999999999
#define INF64 1999999999999999999
#define ALL(n) n.begin(),n.end()
#define ABS(a,b) max(a,b) - min(a,b)
int s[1145151];
int main() {
	int n,a,ans;
	cin >> n;
	a = n;
	s[n] = 1;
	FOR(i,2, INF) {
			if (n % 2 == 0)n /= 2;
			else n = 3 * n + 1;
			if (s[n] > 0) {
				ans = i;
				break;
			}
			else s[n] = i;
	}
	cout << ans << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <set>
#include <iomanip>
using namespace std;
int main() {
	string h;
	cin >> h;
	for (int i = 0; i < h.length(); ++i) {
		if (h[i] == '9') cout << "1";
		else cout << "9";
	}
}

Measured memory_bytes: 256
#!/usr/bin/env python3
import sys

YES = "Yes"  # type: str
NO = "No"  # type: str

def solve(N: int, H: "List[int]"):
    for i in range(N-2, -1, -1):
        if H[i] == H[i+1] + 1:
            if i > 0:
                if H[i] >= H[i-1]:
                    H[i] -= 1
            else:
                H[i] -= 1
        if H[i] > H[i+1]:
            print(NO)
            return
    print(YES)
    return


# Generated by 1.1.4 https://github.com/kyuridenamida/atcoder-tools  (tips: You use the default template now. You can remove this line by using your custom template)
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    N = int(next(tokens))  # type: int
    H = [ int(next(tokens)) for _ in range(N) ]  # type: "List[int]"
    solve(N, H)

if __name__ == '__main__':
    main()


Measured memory_bytes: 60576
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ull = unsigned long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using Graph = vector<vector<pii>>;
using mat = vector<vector<int>>;
const int MOD = 1e9 + 7;

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

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

    vector<ll> dp(H + 1, 1e18);
    dp[0] = 0;
    for (int i = 0; i < N; ++i) {
        for (int j = 0; j < H; ++j) {
            int tmp = min(A[i] + j, H);
            dp[tmp] = min(dp[j] + B[i], dp[tmp]);
        }
    }

    cout << dp[H] << endl;

    return 0;
}


Measured memory_bytes: 384
#include<iostream>
#include<string>
#include<algorithm>
#include<map>
#include<set>
#include<utility>
#include<vector>
#include<cmath>
#include<cstring>
#include<cstdio>
#include<time.h>
#define loop(i,a,b) for(int i=a;i<b;i++) 
#define rep(i,a) loop(i,0,a)
#define pb push_back
#define mp make_pair
#define all(in) in.begin(),in.end()
const double PI=acos(-1);
const double EPS=1e-10;
using namespace std;
typedef long long ll;
typedef vector<int> vi;
int main(){
	string in[8];
	int n=8;
	rep(i,8)cin>>in[i];
	cout<<90<<endl;
	rep(i,n){rep(j,n)cout<<in[7-j][i];cout<<endl;}
	cout<<180<<endl;
	rep(i,n){rep(j,n)cout<<in[7-i][7-j];cout<<endl;}
	cout<<270<<endl;
	rep(i,n){rep(j,n)cout<<in[j][7-i];cout<<endl;}	
}

Measured memory_bytes: 1188