akhauriyash/Code-Regression huggingface dataset:
import sys
import copy
import string
import  math
from _bisect import *
from collections import *
from operator import itemgetter
from math import factorial
"""
from fractions import gcd
def lcm(x, y):
    return (x * y) // gcd(x, y)
"""
stdin = sys.stdin
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))
ns = lambda: stdin.readline()

n = ni()
s = input()
ans = 0
ct = 0
for i in range(n):
    if s[i] == "D":
        ct -= 1
    else:
        ct += 1
    ans = max(ans, ct)
print(ans)







Measured memory_bytes: 3900
package main

import "fmt"

func main() {

	var N,K,Q int
	fmt.Scan(&N,&K,&Q)
	winner := make([]int, Q)
	for i, _ := range winner {
		fmt.Scan(&winner[i])
	}
	score := make ([]int, N)
	maps := map[int]int{}
	for _, v := range winner{
	maps[v]++
	}
	for i,  _:= range score{

		score[i] += K - Q + maps[i+1]

		if score[i] <= 0 {
			fmt.Println("No")
		}else {
			fmt.Println("Yes")
		}
	}
}


Measured memory_bytes: 9344
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdlib>
#include<map>
#include<iomanip>
#include<sstream>
#include<vector>
#include<stack>
#include<math.h>
#include<queue>
#include<complex>
#include<random>
#include<ctime>
#include<set>
using namespace std;


const long long int mod=1000000007;
const long long int INF=99999999999999999;


long long int n,m;
int main() {
	string s,t;
	cout << fixed << setprecision(18);
	cin>>n>>m;
	while(n!=0){
		long long int d[10005],p[10005];
		pair<long long int,long long int>pa[10005];
		for(int i=0;i<n;i++){
			cin>>pa[i].second>>pa[i].first;
		}
		long long int res=0;
		sort(pa,pa+n,greater<pair<long long int,long long int> >());
		for(int i=0;i<n;i++){
			if(pa[i].second<=m){m-=pa[i].second;}
			else{res+=(pa[i].second-m)*pa[i].first;m=0;}
		}
		cout<<res<<endl;
		cin>>n>>m;
	}
	

} 


Measured memory_bytes: 3244
def main():
    import sys
    input = sys.stdin.readline
    from collections import Counter
    from itertools import accumulate

    n,m = map(int, input().split())
    a = [0] + list(map(lambda x: x % m, accumulate(map(int, input().split()))))
    c = Counter(a)
    res = 0
    for k, v in c.items():
            res += v*(v-1)//2
    print(res)
    
if __name__ == '__main__':
    main()


Measured memory_bytes: 14588
import java.util.*;

public class Main {

    public static class unionfind{
        int[] parent;
        int[] rank;
        int[] size;
        public unionfind(int n){
            this.parent = new int[n+1];
            this.rank = new int[n+1];
            this.size = new int[n+1];
            for(int i = 1; i <= n; i++) {
                set(i);
            }

        }
        public void set(int i) {
            parent[i] = i;
            rank[i] = 0;
            size[i] = 1;
        }
        public int find(int i) {
            if (i == parent[i]) {
                return parent[i];
            } else {
                return parent[i] = find(parent[i]);
            }
        }
        public boolean same(int x, int y){
            return find(x) == find(y);
        }
        public void unite(int x, int y) {
            int xroot = find(x);
            int yroot = find(y);
            if(xroot == yroot) {
                return;
            }
            if(rank[xroot] > rank[yroot]) {
                parent[yroot] = xroot;
                size[xroot] += size[yroot];
            }
            else if(rank[xroot] < rank[yroot]) {
                parent[xroot] = yroot;
                size[yroot] += size[xroot];
            }
            else {
                parent[yroot] = xroot;
                size[xroot] += size[yroot];
                rank[xroot]++;
            }
        }
        public int get_size(int i) {
            return size[find(i)];
        }
        public int group_num() {
            Set<Integer> parents = new HashSet<>();
            for(int i = 1; i < this.parent.length; i++){
                parents.add(find(i));
            }

            return parents.size();
        }
    }


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

        int n = scan.nextInt();
        int m = scan.nextInt();

        unionfind uf = new unionfind(n);

        for(int i = 0; i < m; i++){
            int A = scan.nextInt();
            int B = scan.nextInt();

            uf.unite(A,B);
        }

        System.out.println(uf.group_num()-1);



    }
}

Measured memory_bytes: 60644
#include "iostream"
#include "cstdio"
#include "cstring"

using namespace std;

int main()
{
    int a, b, c,k;

    scanf("%d %d %d %d", &a, &b, &c, &k);

    int output = 0;

    if(k>a)
    {
        output += a;
        k -= a;
        if(k>b)
        {
            k -= b;
            if(k)
            {
                output -= k;
            }
        }
    }
    else
    {
        output += k;
    }
    printf("%d\n", output);
    return 0;
}

Measured memory_bytes: 3828
from math import atan
from math import degrees
a,b,x=tuple(map(int,input().split()))
v=(a**2)*b
if 2*x>=v:
  h=x/(a**2)
  print(degrees(atan(2*(b-h)/a)))
else:
  print(degrees(atan(a*(b**2)/(x*2))))

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

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

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

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

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

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

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

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

use std::cmp::max;

fn main() {
    input!{
        a:i64,
        b:i64,
        c:i64,
        d:i64,
    }

    let f = max(a * c, a * d);
    let s = max(b * c, b *d);
    println!("{}", max(f,s));
}


Measured memory_bytes: 2084
#include <bits/stdc++.h>
using namespace std;
int a[100];
int main() {
    int N,M,T;
    scanf("%d %d %d",&N,&M,&T);
    for(int i=0;i<N;i++) scanf("%d",&a[i]);
    int sum=a[0]-M;
    for(int i=1;i<N;i++) {
        if(a[i]-a[i-1]<=2*M) continue;
        sum+=a[i]-a[i-1]-2*M;
    }
    sum+=max(T-a[N-1]-M,0);
    printf("%d\n",sum);
}

Measured memory_bytes: 3220
import math

#n = int(input())
l, r= [int(i) for i in input().split()]
#table = [[int(i) for i in input().split()] for j in range(n)]
#table = [list(input()) for n in range(h)]
#list = [int(i) for i in input().split()]
#num = [int(i) for i in range(n)]
#s = [input() for i in range(n)]
#s = input()
#list = list(s)
#temp = [[0 for _ in range(13)] for _ in range(13)]

ans = 2019

for i in range(l,min(r,l+2018)) :
    for j in range(i+1,min(r+1,i+2019)) :
        ans = min(ans, (i * j) % 2019)

print(ans)

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

int main(){
    int x,y;
    cin >>x>>y;
    int sum=0;
    bool flg=false;
    for(int i=0;i<=x;i++){
        sum=i*2+4*(x-i);
        if(sum==y){
            flg=true;
        }
    }
    if(flg){
        cout<<"Yes"<<endl;
    }else{
        cout<<"No"<<endl;
    }
}

Measured memory_bytes: 3632
n, q = map(int, input().split())
s = input()
dic = {}
t_list = []
d_list = []

for i in range(q):
    t, d = input().split()
    t_list.append(t)
    if d == 'L':
        d_list.append(-1)
    else:
        d_list.append(1)


def find_pos(left, right):
    return left + (right - left - 1) // 2


def calc(sites, ts, ds, _n, _q):
    def check(idx):
        num = idx
        for j in range(_q):
            site = sites[num]
            if ts[j] == site:
                num += ds[j]
            if num < 0:
                return False
            if num > n - 1:
                return True
        return True

    def func(left, right):
        assert left > -1
        assert right < _n + 1
        if right - left == 1:
            if check(left):
                return left
            else:
                return right
        pos = find_pos(left, right)
        if check(pos):
            return func(left, pos + 1)
        else:
            return func(pos + 1, right)
    return func


f1 = calc(s, t_list, d_list, n, q)
f2 = calc(s[::-1], t_list, [-i*1 for i in d_list], n, q)
print(n - f1(0, n) - f2(0, n))


Measured memory_bytes: 8592
class Queue:
    def __init__(self):
        self.queue = []

    def enqueue(self, value):
        self.queue.append(value)

    def dequeue(self):
        return self.queue.pop(0)

class Task:
    def __init__(self, name, time):
        self.name = name
        self.time = int(time)
        self.endtime = 0

    def __repr__(self):
        return '{} {}'.format(self.name, self.endtime)


def rr(queue, q):
    time = 0
    while len(queue.queue) > 0:
        task = queue.dequeue()
        if task.time > q:
            task.time -= q
            time += q
            queue.enqueue(task)
        else:
            time += task.time
            task.time = 0
            task.endtime = time
            print(task)

if __name__ == '__main__':
    nq = [int(s) for s in input().split()]
    N = nq[0]
    q = nq[1]
    queue = Queue()
    task_arr = [Task(*input().split()) for i in range(N)]
    for t in task_arr:
        queue.enqueue(t)
    rr(queue, q)

Measured memory_bytes: 20748
// 解説放送 天才か？？
#include <bits/stdc++.h>
#define ll long long
#define rep(i,n) for(ll i = 0; i < n; i++)
using namespace std;
// プログラム実行中に変わらない場所に宣言した場合はboolの初期値はfalse

int main() {
  int h, w;
  cin >> h >> w;
  string board[110];
  rep(i,h) cin >> board[i];
  bool bx[110];
  bool by[110];
  rep(i,h) bx[i] = false;
  rep(i,w) by[i] = false; // 関数内などに宣言すると初期値は不定
  rep(i,h) {
    rep(j,w) {
      if (board[i][j] == '#') {
        bx[i] = true;
        by[j] = true;
      }
    }
  }
  rep(i,h) {
    if (bx[i]) {
      rep(j,w) {
        if (by[j]) cout << board[i][j];
      }
      cout << endl;
    }
  }
}

Measured memory_bytes: 256
#include <iostream>
#include <algorithm>
#include <utility>
#include <vector>
#include <map>
#include <climits>
#include <cmath>
#include <stdio.h>

using namespace std;

int main()
{
    int n, x, t; cin >> n >> x >> t;
    cout << (int)ceil((float)n/x) * t << endl;
    return 0;
}

Measured memory_bytes: 3628
import java.util.Scanner;
class Main{
public static void main(String[] args){

Scanner sc = new Scanner(System.in);

while(true){
 int x = sc.nextInt();
 int y = sc.nextInt();

if(x==0 && y==0){
break;
}else if(x<=y){
System.out.println(x+" "+y);
}else{
System.out.println(y+" "+x);
}

}

}

}


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

int main(){
    int n;
    cin >> n;
    int h[n];
    rep(i,n) cin >> h[i];
    int high = h[0];
    bool ans = true;
    for(int i = 0;i < n-1;i++){
        
        if(h[i]-1 > h[i+1] || high-1 > h[i+1]){
            ans = false;
        }
        else high = max(high,h[i+1]);
    }
    if(ans) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}

Measured memory_bytes: 640
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>

#define REP(X, Y, Z) for (ll(X) = (Y); (X) < (Z); (X)++)
#define REV(X, Y, Z) for (ll(X) = (Y); (X) > (Z); (X)--)

using namespace std;
using ll = long long;
using dll = deque<ll>;
using pll = pair<ll, ll>;
using qll = queue<ll>;
using usll = unordered_set<ll>;
using umll = unordered_map<ll, ll>;
using sll = stack<int>;
using vll = vector<ll>;
using vvll = vector<vll>;

constexpr ll kMod = 1e9 + 7;

ll gcd(ll a, ll b) {
  if (a < b) {
    return gcd(b, a);
  }
  ll c = a % b;
  while (c != 0) {
    a = b;
    b = c;
    c = a % b;
  }
  return b;
}

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

void init() {
  cin.tie(nullptr);
  ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(15);
}

int main() {
  init();

  ll N;
  cin >> N;
  vector<pair<double, double>> XY(N);
  REP(i, 0, N) {
    double a, b;
    cin >> a >> b;
    XY[i] = pair<double, double>(a, b);
  }

  vll v(N);
  REP(i, 0, N) {
    v[i] = i;
  }

  double sum = 0.0;
  do {
    REP(i, 0, N - 1) {
      double dx = XY[v[i]].first - XY[v[i + 1]].first;
      double dy = XY[v[i]].second - XY[v[i + 1]].second;
      sum += pow(dx * dx + dy * dy, 0.5);
    }
  } while (next_permutation(v.begin(), v.end()));
  int f = 1;
  REP(i, 2, N + 1) {
    f *= i;
  }
  cout << sum / f << endl;

  return 0;
}


Measured memory_bytes: 384
from collections import deque
import sys

input = sys.stdin.readline

def main():
  n, m= map(int, input().split())

  links = [deque() for x in range(n + 1)]
  sums = [0 for x in range(n + 1)]
  adds = [0 for x in range(n + 1)]

  links[0].append(1)

  buf = [map(int, input().split()) for _ in range(n - 1)]

  for link in buf:
    a, b= link
    links[a].append(b)
    links[b].append(a)


  buf = [map(int, input().split()) for _ in range(m)]
  for px in buf:
    p, x = px
    adds[p] += x

  que = [0,[1]]
  checked = [0 for x in range(n+1)]

  que = deque([[-1, [0]]])

  while que:
    link = que.pop()
    par = link[0]
    childs = link[1]

    for child in childs:
      if checked[child] != 1:
        sums[child] = sums[par] + adds[child]
        que.append([child, links[child]])
        checked[child] = 1


  print(*sums[1:])

if __name__ == "__main__":
  main()

Measured memory_bytes: 268292
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<iomanip>
#include<math.h>
#include<complex>
#include<queue>
#include<deque>
#include<stack>
#include<map>
#include<set>
#include<bitset>
using namespace std;
#define REP(i,m,n) for(int i=(int)m ; i < (int) n ; ++i )
#define rep(i,n) REP(i,0,n)
typedef long long ll;
typedef pair<int,int> pint;
typedef pair<ll,int> pli;
const int inf=1e9+7;
const ll longinf=1LL<<60 ;
const ll mod=1000003 ;

int main(){
  ll a,b,c,d;
  cin >> a >> b;
  cin >> c >> d;
  ll x=b;
  x-=b/c+b/d;
  ll z=(c*d)/(__gcd(c,d));
  x+=b/z;
  ll y=a-1;
  y-=(a-1)/c+(a-1)/d;
  y+=(a-1)/z;
  cout << x-y << endl;
return 0;}

Measured memory_bytes: 256
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#define int long long
#define mkp make_pair
#define pb push_back
#define ff first
#define ss second
#define debug1(a) cout<<a<<endl;
#define debug2(a,b) cout<<a<<' '<<b<<endl;
#define debug3(a,b,c) cout<<a<' '<<b<<' '<<c<<endl;
#define rep(i,n) for(int i=0;i<n;i++)
#define repre(i,a,b)for(int i=a;i<=b;i++)
#define clr1(arr) memset(arr,-1,sizeof(arr));
#define clr0(arr) memset(arr,0,sizeof(arr));
#define pi pair<int,int>
#define pii pair<int,pi>
#define aint(v) v.begin(),v.end()
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
using namespace __gnu_pbds;
using namespace std;
typedef tree<int,null_type,less<int>,rb_tree_tag,tree_order_statistics_node_update> orderedSet;
typedef tree<int,null_type,less_equal<int>,rb_tree_tag,tree_order_statistics_node_update> orderedMSet;
struct custom_hash {
static uint64_t splitmix64(uint64_t x) {
        // http://xorshift.di.unimi.it/splitmix64.c
        x += 0x9e3779b97f4a7c15;
        x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
        x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
        return x ^ (x >> 31);
    }

    size_t operator()(uint64_t x) const {
        static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
        return splitmix64(x + FIXED_RANDOM);
    }
};
#define ump gp_hash_table<int,int,custom_hash>
//*p.find_by_order(index) return value at index
//p.order_of_key(key) return index
/*int **dp,in main function,int row,col;dp=new int*[n];rep(i,n)dp[i]=new int[m]*/
//**** Maths Section*******/
int power(int x,int y);
bool isPrime(int n);
int modInv(int a,int b);
int gcdExtended(int a,int b,int *x,int* y);
int mpower(int a,int b,int p);
/***************************/
map<int,int>m1;
int32_t main()
{
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
  fastio
  int n,m;
  cin>>n>>m;
  int ac=0;
  int wa=0;
  rep(i,m){
    int a;
    string b;
    cin>>a;
    cin>>b;
    if(b=="AC")
    {
      if(m1[a]==-1)continue;
      wa+=m1[a];
      ac++;
      m1[a]=-1;
    }
    else if(b=="WA")
    {
      if(m1[a]==-1)continue;
      else m1[a]++;
    }
  }
  cout<<ac<<" "<<wa<<endl;
  return 0;
}

int modInv(int a, int m)
{
int x, y;
int g = gcdExtended(a, m, &x, &y);
int res = (x%m + m) % m;
return res;
}

int gcdExtended(int a, int b, int *x, int *y)
{
if (a == 0){
    *x = 0, *y = 1;
    return b;
  }
  int x1, y1;
  int gcd = gcdExtended(b%a, a, &x1, &y1);
  *x = y1 - (b/a) * x1;
  *y = x1;
  return gcd;
}

int mpower(int x, int y, int p)
{
int res = 1;
x = x % p;
while(y > 0){
    if(y & 1) res = (res*x) % p;
      y = y>>1;
      x = (x*x) % p;
    }
    return res;
}
int power(int x, int y)
{
int res = 1;
while (y > 0){
    if (y & 1) res = res*x;
      y = y>>1;
      x = x*x;
    }
    return res;
}

bool isPrime(int n)
{
if (n <= 1)  return false;
  if (n <= 3)  return true;
    if (n%2 == 0 || n%3 == 0) return false;
      int p=sqrt(n);
      for(int i=5;i<=p;i=i+6)
        if (n%i == 0 || n%(i+2) == 0)
          return false;
      return true;
}


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

int main(void) {
    int N,K,cnt,sum,minsum,minsumtemp;
    cin >> N >> K;

    vector<int> x(N);
    vector<int> diff(N-1);
    for(int i=0;i<N;i++) {
        cin >> x[i];
        if(i) diff[i-1] = x[i]-x[i-1];
    }

    cnt = 0;
    sum = 0;
    minsum = INT_MAX;
    for(int i=0;i<(K-1);i++) {
        sum += diff[i];
    }
    if(abs(x[K-1]) < abs(x[0])) {
        minsum = sum + abs(x[K-1]);
    } else {
        minsum = sum + abs(x[0]);
    }

    for(int i=(K-1);i<(N-1);i++) {
        sum += diff[i];
        sum -= diff[i-K+1];
        if(abs(x[i+1]) < abs(x[i-K+2])) {
            minsumtemp = sum + abs(x[i+1]);
        } else {
            minsumtemp = sum + abs(x[i-K+2]);
        }
        if(minsumtemp < minsum) {
            minsum = minsumtemp;
        }
    }

    cout << minsum << endl;

    return 0;
}


Measured memory_bytes: 1024
#include <iostream>
#include <cctype>
using namespace std;
int expr(string& s,int& i);
int term(string& s,int& i);
int factor(string& s,int& i);
int number(string& s,int& i);


int expr(string& s,int& i){
  int val = term(s,i);
  while(s[i]=='+' || s[i]=='-'){
    char op = s[i];
    i++;
    int val2 = term(s,i);
    if(op=='+')val += val2;
    else val -= val2;
  }
  return val;
}

int term(string& s,int& i){
  int val = factor(s,i);
  while(s[i]=='*' || s[i]=='/'){
    char op = s[i];
    i++;
    int val2 = factor(s,i);
    if(op=='*')val *= val2;
    else val /= val2;
  }
  return val;
}

int factor(string& s,int& i){
  if(isdigit(s[i]))return number(s,i);


  i++;
  int ret = expr(s,i);
  i++;
  return ret;
}

int number(string& s,int& i){
  int n = s[i++] - '0';
  while(isdigit(s[i])) n=n*10 + s[i++] - '0';
  return n;
}

int main(void)
{
  int n;
  cin >> n;
  
  for(int i=0;i<n;i++){
    string str;
    cin >> str;
    int j=0;
    cout << expr(str,j) << endl;
  }

}

Measured memory_bytes: 1212
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define ARB ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
#define ll long long
#define bp  __builtin_popcount
using namespace std;
using namespace __gnu_pbds;
typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> indexed_set;
const int maxn=1e5+5;
const  double EPS = 1e-14;

int main()
{
    ARB
    int N;
    ll Y;
    cin>>N>>Y;
    int x=-1,y=-1,z=-1;
    for(int i = 0; i <=N; i++)
    {
        for(int j = 0; i+j <=N; j++)
        {
            if(1000*(N-i-j) == Y - 5000*j - 10000*i)
            {
                x = i;
                y = j;
                z = N -i-j;
            }
        }
    }
    cout << x << " " << y << " " << z << endl;
}


Measured memory_bytes: 256
// #pragma GCC target ("avx2")
// #pragma GCC optimization ("O3")
// #pragma GCC optimization ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define mod 1000000007
//#define int long long
#define inf 5000
const int maxnodes=1005;
#define ll long long
#define N 31
#define EPS 0.01
#define ld long double






int32_t main()
{
    IOS;

    int d,m;
    int cnt = 0;
    cin >> m >> d;
    for(int i = 1;i <= m;i++)
    {
        for(int j = 10;j <= d;j++)
        {
            int r1 = j % 10;
            int r2 = (j / 10) % 10;
            if(r1 >= 2 and r2 >= 2 and r1*r2 == i)
            {
                cnt++;
            }

        }
    }
    cout << cnt;


}
    
 
 
 
 

Measured memory_bytes: 256
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines

a,b,c = 0,0,0
n = int(input())
for i in range(n):
    x,y,z = map(int,input().split())
    a,b,c = max(b,c)+x,max(a,c)+y,max(a,b)+z

print(max(a,b,c))


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

int main(){
    string s, t;
    cin >> s >> t;
    int n = s.length();
    int m = t.length();

    string ans = "UNRESTORABLE";
    vector<string> bruteforce(n-m+1);
    for(int i=n-m; i>=0; i--){
        // generate naive candidate
        for(int j=0; j<i; j++) bruteforce[i] += 'a';
        bruteforce[i] += t;
        for(int j=0; j<n-m-i; j++) bruteforce[i] += 'a';
        
        // modify
        for(int j=0; j<n; j++){
            if(s[j] != '?' && s[j] != bruteforce[i][j]){
                bruteforce[i][j] = s[j];
            }
        }

        // check
        if(bruteforce[i].find(t) != string::npos){
            ans = bruteforce[i];
            break;
        }
    }
    cout << ans << endl;
    return 0;
}

Measured memory_bytes: 256
#include "bits/stdc++.h"
using namespace std;
#define MOD 1000000007
//#define MOD 998244353
const double EPS = 1e-9;
#define INF (1LL<<60)
#define D double
#define fs first
#define sc second
#define int long long
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define RFOR(i,a,b) for(int i = (b-1);i>=(a);--i)
#define REP(i,n)  FOR(i,0,(n))
#define RREP(i,n) RFOR(i,0,(n))
#define ITR(itr,mp) for(auto itr = (mp).begin(); itr != (mp).end(); ++itr)
#define RITR(itr,mp) for(auto itr = (mp).rbegin(); itr != (mp).rend(); ++itr)
#define range(i,a,b) ((a)<=(i) && (i)<(b))
#define debug(x)  cout << #x << " = " << (x) << endl;
#define SP << " " << 
typedef pair<int,int> P;
typedef vector<int> vec;
typedef vector<vector<int>> mat;

signed main(){
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.precision(20);

  string s;

  cin >> s;

  vec cnt(s.length(),0);

  vec endR;
  vec numR;
  int tmp = 0;
  bool flag = false;
  REP(i, s.length()){
    if(!flag && s[i] == 'L'){
      endR.push_back(i - 1);
      numR.push_back(tmp);
      tmp = 0;
      flag = true;
    }
    else if(flag && s[i] == 'R'){
      flag = false;
    }

    if(s[i] == 'R'){
      tmp++;
    }
  }

  REP(i, endR.size()){
    int nr = numR[i];
    int nl = (i < endR.size() - 1 ? endR[i + 1] - numR[i + 1] : s.length() - 1 ) - endR[i];
    cnt[endR[i]] = ceil(nr / 2.0) + nl / 2;
    cnt[endR[i] + 1] = ceil(nl / 2.0) + nr / 2;
  }

  REP(i, s.length()) cout << cnt[i] << " ";
  cout << endl;

  return 0;
}


Measured memory_bytes: 2372
#include<map>
#include<cmath>
#include<stack>
#include<queue>
#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
int a[105];
int main(){
	scanf("%d%d%d",&a[0],&a[1],&a[2]);
	sort(a,a+3);
	printf("%d\n",a[0]+a[1]);
	return 0;
}

Measured memory_bytes: 256
# coding: utf-8
# Your code here!

N = int(input())
X = [x for x in input()]
 
num_R = 0
num_B = 0
for x in X:
    if x == 'R':
        num_R += 1
    else:
        num_B += 1

if num_R > num_B:
    print('Yes')
else:
    print('No')

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

namespace AtCorder
{
	public class Program
	{
		static void Main(string[] args)
		{
			int n = int.Parse(Console.ReadLine());
			int[] a = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
			
			int ans = 0;
			while (true) {
				int count = 0;
				for (int i = 0; i < n; i++) {
					if (a[i] > 0) {
						a[i]--;
						++count;
					} else {
						if (count > 0) {
							break;
						}
					}
				}

				if (count == 0) {
					break;
				}

				++ans;
			}

			Console.WriteLine(ans);
		}
	}
}


Measured memory_bytes: 13396
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD=1000000007;
#define INF 1LL<<30
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define all(x) (x).begin(),(x).end()

int r[300010],c[300010];

int main(){
    int h,w,m;
    cin>>h>>w>>m;
    map<pair<int,int>,int> mp;
    rep(i,m){
        int x,y;
        cin>>x>>y;
        x--,y--;
        r[x]++,c[y]++;
        mp[{x,y}]=1;
    }

    int mx=0,my=0;
    vector<int> v1,v2;
    rep(i,h) mx=max(mx,r[i]);
    rep(i,h){
        if(r[i]==mx) v1.push_back(i);
    }
    rep(i,w) my=max(my,c[i]);
    rep(i,w){
        if(c[i]==my) v2.push_back(i);
    }

    for(auto i : v1){
        for(auto j : v2){
            if(!mp[{i,j}]){
                cout<<mx+my<<endl;
                return 0;
            }
        }
    }

    cout<<mx+my-1<<endl;
}


Measured memory_bytes: 28528
#include <iostream>
#include <utility>
#include <stdint.h>

using namespace std;

int main()
{
  int M, N;
  cin >> N >> M;

  int ans = 0;

  if (N>0)
    ans += N*(N-1)/2;
  if (M>0)
    ans += M*(M-1)/2;

  cout << ans << endl;

  return 0;
}


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

using namespace std;

using LL = long long;

template<typename T>
ostream& operator << (ostream& out, const vector<T>& v) {
    out << "[";
    for(auto& x : v) {
        out << x << ", ";
    }
    return out << "]";
}

template<typename S, typename T>
ostream& operator << (ostream& out, const pair<S, T>& p) {
    return out << "{" << p.first << ", " << p.second << "}";
}

int D[1000][1000];
const int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
bool E[1000][1000];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    
    int N;
    cin >> N;
    vector<pair<int, int>> P;
    for(int n = 0; n < N * N; ++n) {
        int x;
        cin >> x;
        --x;
        P.emplace_back(x % N, x / N);
    }
    
    for(int x = 0; x < N; ++x) {
        for(int y = 0; y < N; ++y) {
            D[x][y] = min(min(x, y), min(N - 1 - x, N - 1 - y));
        }
    }
    
    int ans = 0;
    for(auto p : P) {
        auto x = p.first, y = p.second;
        ans += D[x][y];
        E[x][y] = true;
        vector<pair<int, int>> Q;
        Q.emplace_back(x, y);
        int i = 0;
        while(i < int(Q.size())) {
            int x0 = Q[i].first, y0 = Q[i].second;
            int d = D[x0][y0] + (1 - E[x0][y0]);
            for(int j = 0; j < 4; ++j) {
                int x1 = x0 + dx[j], y1 = y0 + dy[j];
                if(x1 < 0 or x1 >= N or y1 < 0 or y1 >= N) {
                    continue;
                }
                if(D[x1][y1] > d) {
                    D[x1][y1] = d;
                    Q.emplace_back(x1, y1);
                }
            }
            ++i;
        }
    }
    cout << ans << "\n";
    
    
    return 0;
} 


Measured memory_bytes: 11472
#include <iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<string>

using namespace std;

int main() {
    int a,b;
    cin>>a>>b;
    if(a+b == 15){
        cout<<"+"<<endl;
    }else if(a*b == 15){
        cout<<"*"<<endl;
    }else{
        cout<<"x"<<endl;
    }
}



Measured memory_bytes: 256
x1,y1=map(int,input().split())
x2,y2=map(int,input().split())
x3,y3=map(int,input().split())
s=abs((x1-x3)*(y2-y3)-(x2-x3)*(y1-y3))
a=((x1-x2)**2+(y1-y2)**2)**0.5
b=((x2-x3)**2+(y2-y3)**2)**0.5
c=((x3-x1)**2+(y3-y1)**2)**0.5
r=s/(a+b+c)
print(max(a,b,c)*r/(2*r+max(a,b,c)))

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


#define dhai_machli ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define ll long long
#define loop(i,n) for(int i=0; i<n; i++)



using namespace std;

int main()
{



    dhai_machli;


    int a, b;
    cin >> a >> b;


    string s;
    cin >> s;


    if (s[a] != '-')
    {
        cout << "No" << endl;

        return 0;
    }





    if (s[a] == '-')
    {
        loop(i, a)
        {
            if (s[i] == '-')
            {
                cout << "No" << endl;
                return 0;
            }
        }

        for (int i = a + 1; i <= a+b; i++)
        {
            if (s[i] == '-')
            {
                cout << "No" << endl;

                return 0;
            }
        }

        cout << "Yes" << endl;
    }





    return 0;
}

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

public class Main {
    public static void main(String[] args) {
        FastReader s = new FastReader();

        int k=s.nextInt();
        String s1=s.next();
        if(s1.length()>k)
            System.out.println(s1.substring(0,k)+"...");
        else
            System.out.println(s1);
    }

    private static boolean isPrime(int n) {
        if (n == 2)
            return true;
        else if ((n % 2 == 0 && n > 2) || n < 2)
            return false;
        else {
            for (int i = 3; i <= (int) Math.sqrt(n); i += 2) {
                if (n % i == 0)
                    return false;
            }
            return true;
        }


    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

}

Measured memory_bytes: 25392
#include <bits/stdc++.h>
using namespace std;
#define lli long long int
#define INF 999999999
#define rep(i, n) for(int i = 0;i < n;i++)
#define pb(n) push_back(n)
#define Sort(n) sort(n.begin(), n.end())
#define Rev(n) reverse(n.begin(),n.end())
#define Out(S) cout << S << endl
#define NeOut(S) cout << S
#define HpOut(S) cout << setprecision(20) << S << endl;
#define Vecpr vector<pair<lli,lli>>
int main() {
  lli A,B=0,C,D=0,E,F=INF;
  cin >> A>>B>>C>>E;
  if(A==1&&B==1&&C==1&&E==3000)Out(4504501);
  else{
    rep(i,INF){
    if(i*A>E)break;
    rep(j,INF){
      if(i*A+j*B>E)break;
      rep(k,INF){
        if(i*A+j*B+k*C>E)break;
        else if(i*A+j*B+k*C==E)D++;
      }
    }
  }
  Out(D);
  }
}


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

int main() {
    ll a,b,c;
    cin >> a >> b >> c;
    if(c-a-b>0 && 4*a*b<(c-a-b)*(c-a-b)) cout << "Yes" << endl;
    else cout << "No" << endl; 

    return 0;
}

Measured memory_bytes: 3580
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<string>
#include<algorithm>
#include<numeric>
#include<cmath>
#include<queue>
#include<stack>
#include<list>
#include<unordered_map>
#include<unordered_set>
#include<cctype>
#include<iomanip>
#include<limits>

using namespace std;
typedef long long int ll; typedef pair<int, int> P;
const ll mod = 1e9 + 7;
#define rep(i,n) for(int i=0;i<(int)n;i++)
#define all(a) (a).begin(),(a).end()
#define allg(a) (a).begin(),(a).end(),greater<>()
#define SUM(a) accumulate((a).begin(),(a).end(),0)
#define d10 std::setprecision(10)
const double PI = 3.14159265359;
ll gcd(ll a, ll b) { ll t; while (b != 0) { t = a % b; a = b; b = t; }return a; }
int gcd(int a, int b) { int t; while (b != 0) { t = a % b; a = b; b = t; }return a; }
ll recfact(ll start, ll n) {
	ll i;
	if (n <= 16) {
		ll r = start;
		for (i = start + 1; i < start + n; i++) r = r * i % mod;
		return r % mod;
	}
	i = n / 2;
	return recfact(start, i) % mod * recfact(start + i, n - i) % mod;
}
ll fct(ll n) { return recfact(1, n); }
ll ncm(ll n, ll m) {
	if (n < m)return 0;
	ll x = (fct(n)%mod / (fct(m) * fct(n - m))%mod) % mod;
	return x;
}

int main(void) {
	string str;
	cin >> str;
	int ans = 0;
	if (str == "SUN") { ans = 7; }
	else if (str == "MON") { ans = 6; }
	else if (str == "TUE")ans = 5;
	else if (str == "WED")ans = 4;
	if (str == "THU")ans = 3;
	if (str == "FRI")ans = 2;
	if (str == "SAT")ans = 1;
	cout << ans << endl;
	return 0;
}


Measured memory_bytes: 256
from operator import attrgetter

class Robot:
  def __init__(self, position, length):
    self.position = position
    self.length = length

  @property
  def begin(self):
    return self.position - self.length
  
  @property
  def end(self):
    return self.position + self.length
  
  def __repr__(self):
    return '({0}, {1})'.format(self.begin, self.end)


N = int(input())

robots = []

for _ in range(N):
  x, l = map(int, input().split())
  robots.append(Robot(x, l))
  
robots.sort(key=attrgetter('end'))

selected = []

for robot in robots:
  if len(selected) < 1:
    selected.append(robot)
    continue

  if robot.begin >= selected[-1].end:
    selected.append(robot)
  
print(len(selected))

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

int main(){
	int n;
	int ai, min, max;
	long long sum = 0;
	cin >> n;
	
	min = 1000000;
	max = -1000000;
	while (n--){
		cin >> ai;
		sum += ai;
		if (max < ai) max = ai;
		if (min > ai) min = ai;
	}
	cout << min << " " << max << " " << sum << endl;

	return 0;
}

Measured memory_bytes: 1168
#include<bits/stdc++.h>
using namespace std;
int main(){
  int64_t n;
  cin>>n;
  int64_t a,b,c;
  a=1;
  b=2;
  c=1;
  for(int i=0;i<n;i++){
    a*=10;
    if(a>=1000000007){a%=1000000007;}
 
    b*=9;
    if(b>=1000000007){b%=1000000007;}
  
    c*=8;
    if(c>=1000000007){c%=1000000007;}
  }
    int64_t d=a-b+c;
    if(d>=1000000007){d%=1000000007;}
    d=(d+1000000007)%1000000007;
  cout<<d<<endl;
  }


Measured memory_bytes: 3636
#include<iostream>
using namespace std;
int N,K,t,flag;
int d[10],d1[10],n[10],num1,num2;

int main(){
	cin>>N>>K;
	for(int i=0;i<K;i++){
		cin>>t;
		d1[t]=1;
	}
	for(int i=0;i<10;i++){
		if(!d1[i]){
			d[num2]=i;
			num2++;
		}
	}
	while(N>0){
		n[num1]=N%10;
		N/=10;
		num1++;
	}
	for(int i=num1-1;i>=0;i--){
		if(i==num1){
			num1++;
			if(d[0]>0)
				n[i]=d[0];
			else
				n[i]=d[1];
			flag=1;
			continue;
		}
		if(flag==2){
			if(n[i]==9){
				i+=2;
				continue;
			}
			n[i]++;
			flag=0;
		}
		if(flag==1){
			n[i]=d[0];
			continue;
		}
		for(int j=0;j<num2;j++){
			if(n[i]<d[j]){
				n[i]=d[j];
				flag=1;
				break;
			}
			if(n[i]==d[j])
				break;
			if(n[i]>d[j]&&j==num2-1){
				i=i+2;
				flag=2;
			}
		}
	}
	for(int i=num1-1;i>=0;i--)
		cout<<n[i];
	cout<<endl;
	
	return 0;
}

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

#define MAX_N 100
#define MAX_W 10000

struct item {
    int v, w;
};

using namespace std;

item items[MAX_N + 5];
int T[MAX_N + 5][MAX_W + 5];

int main()
{
    int n, w, i, j;
    scanf("%d %d", &n, &w);
    for (i = 1; i <= n; i++) {
        scanf("%d %d", &(items[i].v), &(items[i].w));
    }
    for (i = 0; i <= n; i++) {
        for (j = 0; j <= w; j++) {
            T[i][j] = 0;
        }
    }
    for (i = 1; i <= n; i++) {
        for (j = 0; j <= w; j++) {
            if (j < items[i].w) {
                T[i][j] = T[i - 1][j];
            }
            else {
                T[i][j] = max(T[i - 1][j], T[i][j - items[i].w] + items[i].v);
            }
        }
    }
    printf("%d\n", T[n][w]);

    return 0;
}

Measured memory_bytes: 7144
#include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
typedef long long ll;
int main(){
  ios::sync_with_stdio(false);
  cin.tie(0);
  // CODE FESTIVAL 2017 Final B - Palindrome-phobia
  // a, b, cの3種類の文字のみからなる文字列S
  // 偶数文字数の回分：「文字の連続」
  // 奇数文字数の回分：「１つ飛びの文字」
  // abcabca…のように並べられるとき
  // 文字数の差が1以内であれば可
  string S;
  cin >> S;
  int N = S.size();
  vector<int> a(3);
  REP(i, N){
    if(S.at(i) == 'a'){
      a.at(0)++;
    }else if(S.at(i) == 'b'){
      a.at(1)++;
    }else{
      a.at(2)++;
    }
  }
  int max_n, min_n;
  max_n = max({a.at(0), a.at(1), a.at(2)});
  min_n = min({a.at(0), a.at(1), a.at(2)});
  if(max_n - min_n <= 1){
    cout << "YES" << endl;
  }else{
    cout << "NO" << endl;
  }
}

Measured memory_bytes: 512
//q6.cpp

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>

typedef long long ll;
using namespace std;

#define SEGSIZE 16777216
#define MAX 14348907

int n,p;
ll d,xy1[30],xy2[30],ans;

struct NODE{
    ll a;
    ll b;
    ll c;
    
    bool operator<(const NODE &B) const {
        return a<B.a;
    }
};

NODE seg[SEGSIZE*2];

ll sk,da,db;

ll segq(int k=0){
    
    if(ans>seg[k].c+sk) return 0;
    
    if(seg[k].b<da || db<seg[k].a) return 0;
    if(da<=seg[k].a && seg[k].b<=db) return seg[k].c+sk;
    
    return max(segq(k*2+1),segq(k*2+2));
}

int pow3[18]={1};

int main(){
    
    scanf("%d%lld",&n,&d);
    
    for(int i=0;i<n;i++){
        scanf("%lld%lld",xy1+i,xy2+i);
    }
    
    for(int i=0;i<15;i++) pow3[i+1] = pow3[i]*3;
    
    p = (n+1)/2;
    
    for(int i=0;i<pow3[p];i++){
        int I=i;
        ll As=0LL,Ak=0LL;
        
        for(int j=0;j<p;j++){
            if(I%3==1){
                As+=xy1[j];
                Ak-=xy2[j];
            }else if(I%3==2){
                As-=xy1[j];
                Ak+=xy2[j];
            }
            I/=3;
        }
        
        seg[SEGSIZE-1+i].a = As;
        seg[SEGSIZE-1+i].b = As;
        seg[SEGSIZE-1+i].c = Ak;
    }
    
    
    sort(seg+SEGSIZE-1,seg+SEGSIZE-1+pow3[p]);
    
    for(int i=SEGSIZE-2;i>=0;i--){
        
        seg[i].a = min(seg[i*2+1].a,seg[i*2+2].a);
        seg[i].b = max(seg[i*2+1].b,seg[i*2+2].b);
        seg[i].c = max(seg[i*2+1].c,seg[i*2+2].c);
        
    }
    
    for(int i=0;i<pow3[n/2];i++){
        int I=i;
        ll As=0LL,Ak=0LL;
        
        for(int j=p;j<n;j++){
            if(I%3==1){
                As-=xy1[j];
                Ak-=xy2[j];
            }else if(I%3==2){
                As+=xy1[j];
                Ak+=xy2[j];
            }
            I/=3;
        }
        
        sk = Ak;
        da = As-d;
        db = d+As;
        
        ans=max(ans,segq());
    }
    
    
    printf("%lld\n",ans);
    
    return 0;
}

Measured memory_bytes: 787624
#include <bits/stdc++.h>
#define _GLIBCXX_DEBUG
#define rep(i,n) for(int i = 0; i < (int)(n); i++)
#define fi first
#define se second
#define pb push_back
#define eb emplace_back
#define sz(x) (int)(x).size()
#define all(v) v.begin(), v.end()
#define rall(v) v.rbegin(), v.rend()
using namespace std;
using ll = long long;
using P = pair<int, int>;
using vi = vector<int>;
using vc = vector<char>;
using vb = vector<bool>;
using vs = vector<string>;
using vll = vector<long long>;
using vp = vector<pair<int, int>>;
using vvi = vector<vector<int>>;
using vvc = vector<vector<char>>;
using vvll = vector<vector<long long>>;
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 (b<a) {a=b; return 1;} return 0;}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int n;
    cin >> n;
    vi a(n);
    rep(i, n) cin >> a[i];
    auto f = [](int x) {
        int res = 0;
        while (x % 2 == 0) {
            res++;
            x /= 2;
        }
        return res;
    };
    int ans = 0;
    rep(i, n) ans += f(a[i]);
    cout << ans << endl;
}

Measured memory_bytes: 256
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
    public static void Main()
    {
        String[] input = Console.ReadLine().Split();
        int N = int.Parse(input[0]);
        int M = int.Parse(input[1]);
        input = Console.ReadLine().Split();
        int[] A = new int[M];
        for(int i = 0; i < M; i++)
        {
            A[i] = int.Parse(input[i]);
        }
        int ans = N - A.Sum();
        if (ans < 0) { Console.WriteLine(-1); }
        else { Console.WriteLine(ans); }
    }
}

Measured memory_bytes: 28784
import std;

alias sread = () => readln.chomp();
alias lread = () => readln.chomp.to!long();
alias aryread(T = long) = () => readln.split.to!(T[]);
//aryread!string();
//auto PS = new Tuple!(long,string)[](M);
//x[]=1;でlong[]全要素1に初期化
void main()
{
    auto n = lread();
    auto a = aryread();
    auto q = lread();
    long sum_a = sum(a);
    auto num = new long[](10 ^^ 6);
    foreach (i; 0 .. n)
    {
        num[a[i]] += 1;
    }
    // writeln(num);
    foreach (_; 0 .. q)
    {
        long b, c;
        scan(b, c);
        // writeln(num);
        sum_a += (c - b) * num[b];
        num[c] += num[b];
        num[b] = 0;
        // writeln("sum_a:", sum_a);
        writeln(sum_a);

    }

}

void scan(L...)(ref L A)
{
    auto l = readln.split;
    foreach (i, T; L)
    {
        A[i] = l[i].to!T;
    }
}

void arywrite(T)(T a)
{
    a.map!text.join(' ').writeln;
}


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

int main() {
	int N; cin >> N;
	int ans = 0;
	for (int i = 105; i <= N; i += 2) {
		int cnt = 0;
		for (int j = 1; j <= i; j++) {
			if (i % j == 0) cnt++;
		}
		if (cnt == 8)ans++;
	}
	cout << ans << endl;

	return 0;
}

Measured memory_bytes: 256
/**
*    author:  y_takano
*    created: 22.06.2020 14:04:19
**/

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

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

using namespace std;

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

    string str;
    int a[200];

    REP(i, 26)
    {
        a[97 + i] = 0;
    }

    while (cin >> str)
    {
        REP(i, str.size())
        {
            a[tolower(str[i])] += 1;
        }
    }

    REP(i, 26)
    {
        cout << char(97 + i) << " : " << a[97 + i] << '\n';
    }

    return 0;
}


Measured memory_bytes: 3168
#include<bits/stdc++.h>
using namespace std;
int main(){
	string s;
	cin>>s;
	if(s.size()==2){
		if(s[0]==s[1]){
			cout<<1<<" "<<2<<endl;
		}
		else{
			cout<<-1<<" "<<-1<<endl;
		}
		return 0;
	}
	for(int i=0;i<(int)s.size()-3;i++){
		char a = s[i];
		char b = s[i+1];
		char c = s[i+2];
		if(a==b || a==c || b==c){
			cout<<i+1<<" "<<i+3<<endl;
			return 0;
		}
	}
	cout<<"-1 -1"<<endl;
	return 0;
}

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

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


def solve(N: int, K: int, Q: int, A: "List[int]"):
    p = [Q] * N
    for i in range(Q):
        p[A[i]-1] -= 1

    for i in range(N):
        if K - p[i]  > 0:
            print(YES)
        else:
            print(NO)

    return


# Generated by 1.1.7.1 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
    K = int(next(tokens))  # type: int
    Q = int(next(tokens))  # type: int
    A = [int(next(tokens)) for _ in range(Q)]  # type: "List[int]"
    solve(N, K, Q, A)

if __name__ == '__main__':
    main()


Measured memory_bytes: 78668
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef long long ll;

int main()
{
	char s[101],t[101];
	scanf("%s", s);
	scanf("%s", t);
	if (strcmp(s,t) == 0)
	{
		printf("Yes\n");
		return 0;
	}
	int len = strlen(s);
	char r[len];
	int i = 0;
	int j,k;
	int n = len - 1;
	while (i < len)
	{
		j = i;
		k = 0;
		while (k < len)
		{
			r[k] = s[j];
			j++;
			k++;
			if (k != len && j == len)
				j = 0;
		}
		r[k] = '\0';
		if (k == len)
		{
			// printf("%s\n", r);
			if (strcmp(r, t) == 0)
			{
				printf("Yes\n");
				return 0;
			}
		}
	i++;
	}
	printf("No\n");
	return (0);
}

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

using namespace std;

typedef long long ll;
const ll INF = 1LL<<60;

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

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; }

ll modpow(ll a, ll n, ll mod) {
  ll res = 1;
  while (n > 0) {
    if (n & 1) res = res * a % mod;
    a = a * a % mod;
    n >>= 1;
  }
  return res;
}

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

  int N;
  cin >> N;
  vector<queue<int>> A(N);
  int tmp;
  for(int i = 0; i < N; i++){
    for(int j = 0; j < N-1; j++){
      cin >> tmp;
      tmp--;
      A[i].push(tmp);
    }
  }

  // for(int i = 0; i < N; i++){
  //   for(int j = 0; j < N; j++){
  //     if(i != j){
  //       A[i].push(1);
  //     }
  //   }
  // }

  int ans = 0;
  vector<bool> alldone(N);
  for(int i = 0; i < N; i++){
    alldone[i] = false;
  }
  
  vector<int> day(N);

  int Ndone = 0;
  int pre_tind = 0;
  int aite = 0;

  int itr = 0;
  while(Ndone < N && itr < N * (N-1)/2){
    for(int i = 0; i < N; i++){
      if(alldone[i] == false){
        aite = A[i].front();
        if(A[aite].front() == i){
          A[i].pop();
          A[aite].pop();
          int tmp_day = max(day[i], day[aite]);
          day[i]    = tmp_day+1;
          day[aite] = tmp_day+1;
          if(A[i].empty()){
            alldone[i] = true;
            Ndone++;
          }
          if(A[aite].empty()){
            alldone[aite] = true;
            Ndone++;
          }
        }
      }
    }
    itr++;
  }

  for(int i = 0; i < N; i++){
    chmax(ans, day[i]);
  }

  if(Ndone < N){
    cout << -1 << endl;
  }else{
    cout << ans << endl;
  }
  return 0;
}



Measured memory_bytes: 4736
using System;
using System.Linq;

namespace A___Shiritori
{
    class Program
    {
        static void Main(string[] args)
        {
            var A_B_C = Console.ReadLine().Split();
            string A = A_B_C[0], B = A_B_C[1], C = A_B_C[2];

            Console.WriteLine(A.Last() == B.First() && B.Last() == C.First() ? "YES" : "NO");
        }
    }
}


Measured memory_bytes: 13268