akhauriyash/Code-Regression huggingface dataset:
#include <bits/stdc++.h>

using namespace std;
using ll = long long;
const int N = 55;
const int M = 20;
vector<int> g[N];
int cross[N][N];
pair<int, int> ed[N];
ll dp[N][(1 << M) + 10];
int dep[N], par[N];
int last;
int n, m;
int full_mask;

void dfs(int u, int p) {
  dep[u] = (p == -1 ? 0 : dep[p] + 1);
  par[u] = p;
  for(int x: g[u]) if(x != p) dfs(x, u);
}

/*
ll rec(int i, int mask) {
  if(mask == full_mask) return 1;
  if(dp[i][mask] != -1) return dp[i][mask];
  ll res = 0;
  for(int x: g[i]) {
    if(1) {
      res += rec(x, mask);
      res += rec(x, mask | cross[i][x]);
    }
  }
  return dp[i][mask] = res;
}
*/

ll rec(int i, int mask) {
  if(i == n - 1) return (mask == full_mask);
  if(dp[i][mask] != -1) return dp[i][mask];
  return dp[i][mask] = rec(i + 1, mask) + rec(i + 1, mask | cross[ed[i].first][ed[i].second]);
}

int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  memset(cross, 0, sizeof cross);
  cin >> n;
  for(int i = 0; i < n - 1; ++i) {
    int u, v;
    cin >> u >> v;
    --u, --v;
    ed[i] = {u, v}; 
    g[u].push_back(v);
    g[v].push_back(u);
  }
  dfs(0, -1);
  cin >> m;
  full_mask = (1 << m) - 1;
  for(int i = 0; i < m; ++i) {
    int a, b;
    cin >> a >> b;
    --a, --b;
    if(dep[a] > dep[b]) swap(a, b);
    while(dep[b] > dep[a]) {
      cross[par[b]][b] |= 1 << i;
      cross[b][par[b]] |= 1 << i;
      b = par[b];
    }
    while(a != b) {
      cross[par[a]][a] |= 1 << i;
      cross[a][par[a]] |= 1 << i;
      cross[par[b]][b] |= 1 << i;
      cross[b][par[b]] |= 1 << i;
      a = par[a];
      b = par[b];
    }
  }
  /*
  for(int i = 0; i < n; ++i) {
    for(int j = i + 1; j < n; ++j) {
      cout << i << " " << j << " " << bitset<4>(cross[i][j]).to_string() << '\n';
    }
  } 
  */
  memset(dp, -1, sizeof dp);
  cout << rec(0, 0) << '\n';
  return 0;
}


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

using namespace std;

struct Node {
    int t, d;
    Node(){}
    Node(int _t, int _d) : t(_t), d(_d){}
    bool operator<(const Node& _r) const {
        return d > _r.d;
    }
};

void solve() {
    int n, k;
    cin >> n >> k;
    vector<Node> a(n);
    for (auto& p: a) {
        cin >> p.t >> p.d;
        p.t--;
    }
    sort(a.begin(), a.end());
    vector<bool> trk(n, false);
    vector<int> stk;
    int type = 0;
    long long sum = 0;
    for (int i = 0; i < k; i++) {
        int t = a[i].t, d = a[i].d;
        if (!trk[t]) {
            trk[t] = true; 
            type++;
        } else {
            stk.push_back(d);
        }
        sum += d;
    }
    long long res = sum + 1ll*type*type;
    for (int i = k; i < n; i++) {
        int t = a[i].t, d = a[i].d;
        if (stk.empty()) break;
        if (trk[t]) continue;
        trk[t] = true;
        type++;
        sum -= stk.back(); stk.pop_back();
        sum += d;
        res = max(res, sum + 1ll*type*type);
    }
    cout << res;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    solve();
    cout << endl;
}


Measured memory_bytes: 1408
#include <stdio.h>

int main(){

  int card[4][13];
  int n,i,j,num;
  char c;
  char shcd[4]={'S','H','C','D'};

  scanf("%d",&n);

  for(i=0;i<4;i++){
    for(j=0;j<13;j++){
      card[i][j]=0;
    }
  }

  for(i=0;i<n;i++){
    scanf(" %c %d",&c,&num);
      if(c=='S')card[0][num-1]=1;
      if(c=='H')card[1][num-1]=1;
      if(c=='C')card[2][num-1]=1;
      if(c=='D')card[3][num-1]=1;
    }

  for(i=0;i<4;i++){
    for(j=0;j<13;j++){
      if(card[i][j]==0){
        printf("%c %d\n",shcd[i],j+1);
      }
    }
  }
  return 0;
}


Measured memory_bytes: 596
#include<bits/stdc++.h>
using namespace std;
//#define int long long
#define fo(a,b) for(int a=0;a<b;a++)
#define Sort(a) sort(a.begin(),a.end())
#define rev(a) reverse(a.begin(),a.end())
#define fi first
#define se second
#define co(a) cout<<a<<endl
#define sz size()
#define bgn begin()
#define en end()
#define pb(a) push_back(a)
#define pop pop_back
#define V vector
#define P pair
#define V2(a,b,c) V<V<int>> a(b,V<int>(c))
#define V2a(a,b,c,d) V<V<int>> a(b,V<int>(c,d))
#define incin(a) int a; cin>>a
//#define min min<int>
//#define max max<int>
template<class T>
 void cou(vector<vector<T>> a){
  int b=a.size();
  int c=a[0].size();
  fo(i,b){
    fo(j,c){
      cout<<a[i][j];
      if(j==c-1)
        cout<<endl;
      else
        cout<<' ';
    }
  }
}
/*template<>
 void cou(vector<vector<char>> a){
  int b=a.size();
  int c=a[0].size();
  fo(i,b){
    fo(j,c){
      cout<<a[i][j];
      if(j==c-1)
        cout<<endl;
      else
        cout<<' ';
    }
  }
}*/
 int wari(int a,int b) {
   if(a%b==0)
     return a/b;
   else
     return a/b+1;
 }
 int keta(int a){
  double b=a;
  b=log10(b);
  int c=b;
  return c+1;
 }
 int souwa(int a){
  return a*(a+1)/2;
 }
 int lcm(int a,int b){
  int d=a,e=b,f;
  if(a<b)
    swap(a,b);
  int c,m=1;
  while(m){
    c=a%b;
    if(c==0){
       f=b;
      m--;
    }
    else{
      a=b;
      b=c;
 }
  }
  return d*e/f;
    }
  int gcm(int a,int b){
      int d=a,e=b,f;
  if(a<b)
    swap(a,b);
  int c,m=1;
  while(m){
    c=a%b;
    if(c==0){
       f=b;
      m--;
    }
    else{
      a=b;
      b=c;
 }
  }
  return f;
  }
 bool prime(int a){
   if(a<2)
     return false;
   else if(a==2)
     return true;
   else if(a%2==0)
     return false;
   double b=sqrt(a);
    for(int i=3;i<=b;i+=2){
      if(a%i==0){
        return false;
      }
    }
   return true;
 }
struct Union{
  vector<int> par;
  Union(int n){
	par= vector<int>(n, -1);
  }
  int find(int x){
    if(par[x]<0)
      return x;
    else
      return par[x]=find(par[x]);
  }
  bool same(int a,int b){
    return find(a)==find(b);
  }
  int Size(int a){
    return -par[find(a)];
  }
  void unite(int a,int b){
    a=find(a);
    b=find(b);
    if(a==b)
      return;
    if(Size(b)>Size(a))
      swap<int>(a,b);
    par[a]+=par[b];
    par[b]=a;
  }
};
int ketas(int a){
  string b=to_string(a);
  int c=0;
  fo(i,keta(a)){
    c+=b[i]-'0';
  }
  return c;
}
/*struct aa{
	vector<int> gt;
  aa(int n){
	gt= vector<int>(n, 1);
  }
	void c(V<int> d,int b){
	if(d[b]==0){
		gt[d[b]-1]++;
		gt[gt.sz-1]++;
	}
	else{
		gt[d[b]-1]++;
		c(d,d[d[b]]-1);
	}
}
void cok(int a){
	cout<<gt[a-1]<<endl;
	fo(i,a-1)
	cout<<gt[i]<<endl;
}
};
*/
signed main(){
	string a,b;
	cin>>a>>b;
	cout<<(a[0]==b[0])+(a[1]==b[1])+(a[2]==b[2])<<endl;
}

Measured memory_bytes: 256
def main():
    H, W, K = map(int, input().split())
    
    if W == 1:
        print(1)
        exit()

    MOD = 10 ** 9 + 7
    dp = [[0] * W for _ in range(H+1)]
    dp[0][0] = 1

    for h in range(H):
        # 1: 線あり、 0: 線なし
        for i in range(2 ** (W-1)):
            # 連続した1がある→隣接する列に線が引かれている
            if bin(i).count('11') >= 1:
                continue
            perm = [k for k in range(W)]
            for j in range(W-1):
                if (i >> j) & 1:
                    perm[j], perm[j+1] = perm[j+1], perm[j]

            for j in range(W):
                dp[h+1][perm[j]] += dp[h][j]
                dp[h+1][perm[j]] %= MOD

    print(dp[H][K-1])



main()

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

typedef long long ll;

int main() {
    char S[1000000];

    cin >> S;
    ll c = 0, t = 0;

    for (char *p = S; *p !='\0'; p++) {
        t += (*p == 'W') * c;
        c += (*p == 'B');
    }

    cout << t << '\n';

    return 0;
}

Measured memory_bytes: 512
fn main() {
    let mut sc = Scanner::new();
    let s: Vec<char> = sc.read::<String>().chars().collect();
    let n = s.len();
    for i in 1..n {
        if s[i - 1] == s[i] {
            println!("{} {}", i, i + 1);
            return;
        }
    }
    for i in 2..n {
        if s[i - 2] == s[i] {
            println!("{} {}", i - 1, i + 1);
            return;
        }
    }
    println!("-1 -1");
}

struct Scanner {
    ptr: usize,
    length: usize,
    buf: Vec<u8>,
    small_cache: Vec<u8>,
}

impl Scanner {
    fn new() -> Scanner {
        Scanner {
            ptr: 0,
            length: 0,
            buf: vec![0; 1024],
            small_cache: vec![0; 1024],
        }
    }

    fn load(&mut self) {
        use std::io::Read;
        let mut s = std::io::stdin();
        self.length = s.read(&mut self.buf).unwrap();
    }

    fn byte(&mut self) -> u8 {
        if self.ptr >= self.length {
            self.ptr = 0;
            self.load();
            if self.length == 0 {
                self.buf[0] = b'\n';
                self.length = 1;
            }
        }

        self.ptr += 1;
        return self.buf[self.ptr - 1];
    }

    fn is_space(b: u8) -> bool {
        b == b'\n' || b == b'\r' || b == b'\t' || b == b' '
    }

    fn read<T>(&mut self) -> T
    where
        T: std::str::FromStr,
        T::Err: std::fmt::Debug,
    {
        let mut b = self.byte();
        while Scanner::is_space(b) {
            b = self.byte();
        }

        for pos in 0..self.small_cache.len() {
            self.small_cache[pos] = b;
            b = self.byte();
            if Scanner::is_space(b) {
                return String::from_utf8_lossy(&self.small_cache[0..(pos + 1)])
                    .parse()
                    .unwrap();
            }
        }

        let mut v = self.small_cache.clone();
        while !Scanner::is_space(b) {
            v.push(b);
            b = self.byte();
        }
        return String::from_utf8_lossy(&v).parse().unwrap();
    }
}


Measured memory_bytes: 4352
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Library;
using static Library.Input;

namespace AtCoderTemplate
{
    class ProgramA
    {
        static void Main()
        {
            var s = Line;

            if (s == "Sunny") System.Console.WriteLine("Cloudy");
            else if (s == "Cloudy") System.Console.WriteLine("Rainy");
            else System.Console.WriteLine("Sunny");
        }
    }
}

namespace Library
{
    class Input
    {
        static IEnumerator<string> enumerator = new string[] { }.AsEnumerable().GetEnumerator();

        public static string Line => Console.ReadLine();

        public static string[] StrArr => Line.Split(' ');

        public static int NextInt => int.Parse(NextWord());

        public static long NextLong => long.Parse(NextWord());

        public static List<int> IntList => StrArr.Select(int.Parse).ToList();

        public static List<long> LongList => StrArr.Select(long.Parse).ToList();

        public static IEnumerable<long[]> TakeLine(int N)
        {
            return Enumerable.Repeat(0, N).Select(_ => Console.ReadLine().Split(' ').Select(long.Parse).ToArray());
        }

        public static string NextWord()
        {
            while (!enumerator.MoveNext())
            {
                enumerator = StrArr.AsEnumerable().GetEnumerator();
            }
            return enumerator.Current;
        }
    }
}


Measured memory_bytes: 13268
using System;
class p
{
  static void Main()
  {
    string[] ipt = Console.ReadLine().Split(' ');
    int X = int.Parse(ipt[0]);
    int Y = int.Parse(ipt[1]);
    int Z = int.Parse(ipt[2]);
    Console.WriteLine(Z.ToString() + " " + X.ToString() + " " + Y.ToString());
  }
}

Measured memory_bytes: 11092
#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i=0; i<(n); ++i)
#define y_n(ans) cout<<(ans?"Yes":"No")<<endl;

int main() {
    int n, k;
    cin >> n >> k;
    vector<int> a(n);
    for (int i=0; i<n; ++i) {
        cin >> a[i];
    }
    for (int i=0; i<n-k; ++i) {
        y_n(a[i] < a[i+k]);
    }
}

Measured memory_bytes: 4048
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<map>
using namespace std;

int P[100010], Y[100010], C[100010];
pair<int, int> PY[100010];
map<int, int> X;

int main() {
  int N, M; cin >> N >> M;
  for (int i = 0; i < M; i++) cin >> P[i] >> Y[i];
  for (int i = 0; i < M; i++) PY[i] = make_pair(P[i], Y[i]);
  sort(PY, PY+M, [](const auto a, const auto b) {
    return a.second < b.second;
  });
  for (int i = 0; i < N; i++) C[i] = 0;
  for (int i = 0; i < M; i++) X[PY[i].second] = ++C[PY[i].first-1];
  for (int i = 0; i < M; i++) printf("%06d%06d\n", P[i], X[Y[i]]);
}

Measured memory_bytes: 10356
n, q = gets.chomp.split(' ').map(&:to_i)
ab = (1..(n - 1)).map { gets.chomp.split(' ').map(&:to_i) }
px = (1..q).map { gets.chomp.split(' ').map(&:to_i) }

tree = Array.new(n) { [] }
answer = Array.new(n, 0)
is_added = Array.new(n, false)

ab.each do |a, b|
  tree[a - 1] << b - 1
  tree[b - 1] << a - 1
end
px.each { |p, x| answer[p - 1] += x }

queue = [0]

until queue.empty?
  p = queue.shift
  is_added[p] = true
  tree[p].each do |i|
    next if is_added[i]
    answer[i] += answer[p]
    is_added[i] = true
    queue << i
  end
end

puts answer.join(' ')


Measured memory_bytes: 50684
import sys
import os
import math
import string

ii = lambda: int(sys.stdin.buffer.readline().rstrip())
il = lambda: list(map(int, sys.stdin.buffer.readline().split()))
fl = lambda: list(map(float, sys.stdin.buffer.readline().split()))
iln = lambda n: [int(sys.stdin.buffer.readline().rstrip()) for _ in range(n)]

iss = lambda: sys.stdin.buffer.readline().decode().rstrip()
sl = lambda: list(map(str, sys.stdin.buffer.readline().decode().split()))
isn = lambda n: [sys.stdin.buffer.readline().decode().rstrip() for _ in range(n)]

lcm = lambda x, y: x * y / math.gcd(x, y)

MOD = 10 ** 9 + 7


def main():
    if os.getenv("LOCAL"):
        sys.stdin = open("input.txt", "r")

    N, M = il()
    A = il()
    ret = N - sum(A)
    print(ret if ret >= 0 else -1)


if __name__ == '__main__':
    main()


Measured memory_bytes: 10756
/*
 * written by Yaqi Zhang (zhang623@wisc.edu)
 * University of Wisconsin-Madison
 * 2020
 */
#include <bits/stdc++.h>

#define INF 0x3f3f3f3f
typedef long long ll;

using namespace std;


int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    int k;
    cin >> k;
    int lo, hi;
    cin >> lo >> hi;
    int valid = false;
    for(int i = lo; i <= hi; ++i) {
        if(i % k == 0) {
            valid = true;
            break;
        }
    }
    cout << (valid ? "OK" : "NG") << endl;
    return 0;
}



Measured memory_bytes: 3644
h,w = map(int,input().split())

mp = []
for i in range(h):
    tmp = list(input())
    tml = []
    for j in range(w):
        tml.append(0 if tmp[j] == "." else 1)
    mp.append(tml)
    
#print(mp)

flg = 0
for i in range(1,h-1):
    for j in range(1,w-1):
        if((mp[i][j] == 1) and (mp[i-1][j]+mp[i+1][j]+mp[i][j-1]+mp[i][j+1] == 0)):
            flg = 1
 #           print("{}, {}".format(i,j))
            break
        
ans = ["Yes","No"]
		
print(ans[flg])

Measured memory_bytes: 3064
N = int(input())
S = list(map(int, input().split()))
Q = int(input())
T = map(int, input().split())


def linearSearch(A, k):
    for a in A:
        if a == k:
            return True
    return False


ans = 0
for t in T:
    ans += 1 if linearSearch(S, t) else 0
print(ans)


Measured memory_bytes: 6544
#include <iostream>
#include <string>

using namespace std;

int main() {
    int N,i;
    string A, B, C;
    cin >> N >> A >> B >> C;
    int counter = 0;

    for (int i; i < N; ++i ){
        if (A[i] == B[i] & B[i] == C[i]);
        else {
            if (A[i] != B[i]) ++counter;
            if (B[i] != C[i]) ++counter;
            if (C[i] != A[i]) ++counter;
            --counter;
        }

    }
    cout << counter << endl;
}


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

int main() {
    int N, M;
    while(cin >> N >> M, N) {
        vector<int> v(N, 0);
        v[0] = 1;
        vector<tuple<int, int, int>> r(M);
        for(int i=0; i<M; ++i) {
            int t, s, d;
            cin >> t >> s >> d;
            r[i] = make_tuple(t, s, d);
        }
        sort(r.begin(), r.end(), [](auto const& t1, auto const& t2) {
            return get<0>(t1) < get<0>(t2);
        });

        for(int i=0; i<r.size(); ++i) {
            if(v[get<2>(r[i])-1] != 1) {
                v[get<2>(r[i])-1] = v[get<1>(r[i])-1];
            }
        }
        int ret = 0;
        for(int i=0; i<v.size(); ++i) {
            if(v[i] == 1) ret++;
        }
        cout << ret << endl;
    }
}


Measured memory_bytes: 3320
#include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
const long double pi = acos(-1.0); 
typedef long long ll;
 
int main() {
	cin.tie(0);
	ios::sync_with_stdio(false);

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

Measured memory_bytes: 3644
parseInt(x) = parse(Int, x)
parseBigInt(x) = parse(BigInt, x)
parseFloat(x) = parse(Float64, x)
parseBigFloat(x) = parse(BigFloat, x)
parseMap(x::Array{SubString{String},1}) = map(parseInt, x)

function main()
    h,w=parseMap(split(readline()))
    s=[chomp(readline()) for i in 1:h]
    dp=[[Inf for i in 1:w] for j in 1:h]
    dp[1][1]=0
    for i in 1:h
        for j in 1:w
            if i>1
                if s[i][j]==s[i-1][j]=='#'
                    dp[i][j]=min(dp[i][j],dp[i-1][j]-1)
                else
                    dp[i][j]=min(dp[i][j],dp[i-1][j])
                end
            end
            if j>1
                if s[i][j]==s[i][j-1]=='#'
                    dp[i][j]=min(dp[i][j],dp[i][j-1]-1)
                else
                    dp[i][j]=min(dp[i][j],dp[i][j-1])
                end
            end
            if s[i][j]=='#'
                dp[i][j]+=1
            end
        end
    end
    println(BigInt(dp[end][end]))
end
main()

Measured memory_bytes: 176656
#include <cstdio>
main(){
	int a[4],ar,br;
	scanf("%d%d%d%d",a,a+1,a+2,a+3);
	ar=*a+a[1]+a[2]+a[3];
	scanf("%d%d%d%d",a,a+1,a+2,a+3);
	br=*a+a[1]+a[2]+a[3];
	printf("%d\n",ar>br?ar:br);
}

Measured memory_bytes: 0
import math
import collections

class abc_155:
    
    def __init__(self):
        pass
    
    def A(self):
       pass
    def B(self):
        pass
        
    def C(self):
        N=int(input())
        S=[input() for i in range(N)]
        c=collections.Counter(S).most_common()
        ans=[]
        ans.append(c[0][0])
        roop=c[0][1]
        
        for i in range(1,len(c)):
            if roop==c[i][1]:ans.append(c[i][0])
            else:break
        ans.sort()
        for i in ans:print(i)
                
    def D(self):
        pass
        
    def E(self):
        pass
    
    def F(self):
        pass
    
    
if __name__=='__main__':
    obj=abc_155()
    obj.C()

Measured memory_bytes: 121680
/*
ID: jerrywcy
TASK: AtCoder ARC Problem C
LINK: https://arc096.contest.atcoder.jp/tasks/arc096_a
LANG: C++
*/
#include <bits/stdc++.h>

using namespace std;

int a,b,c,x,y,z;
int ans;

int main()
{
	cin>>a>>b>>c>>x>>y;
	ans+=(min(x,y))*(min(a+b,c*2));
	if (x>y){
		x-=y;
		ans+=min(c*2*x,a*x);
	}
	else if (y>x){
		y-=x;
		ans+=min(c*2*y,b*y);
	}
	cout<<ans<<endl;

	return 0;
}



Measured memory_bytes: 256
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <set>
#include <vector>

using namespace std;

int A,B,C,X,Y;

// A+B <= 2C
void solve1(){
    int ans = A*X + B*Y;
    cout << ans << endl;
    return;
}

// A + B > 2C
void solve2() {
    int ans = 0;
    int c_cnt = X < Y ? 2*X : 2*Y; //C を買う数
    ans += C*c_cnt;
    if (X < Y) {
        if (C*2*(Y-X) < (Y-X)*B ) ans += 2*C*(Y - X);
        else ans += B*(Y-X);
    } else {
        if (C*2*(X-Y) < (X-Y)*A) ans += 2*C*(X - Y);
        else ans += A*(X-Y);
    }
    cout << ans << endl;
    return;
}

int main(){
    scanf("%d %d %d %d %d", &A, &B, &C, &X, &Y);
    if (A+B <= 2*C) solve1();
    else solve2();
    return 0;
}


Measured memory_bytes: 256
// https://atcoder.jp/contests/agc016/tasks/agc016_b

#include "algorithm"
#include "bitset"
#include "cmath"
#include "functional"
#include "iomanip"
#include "iostream"
#include "map"
#include "numeric"
#include "queue"
#include "set"
#include "string"
#include "vector"
#define rep(i, to) for (ll i = 0; i < (to); ++i)
#define rep1(i, to) for (ll i = 1; i <= (to); ++i)
#define repf(i, from, to) for (ll i = from; i < (to); ++i)
#define repr(i, from) for (ll i = from - 1; i >= 0; --i)
#define all(vec) vec.begin(), vec.end()
#define unless(cond) if (!(cond))
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef long double ld;
template <typename T>
using V = vector<T>;
using VL = V<ll>;
using VVL = V<VL>;
template <typename T, typename U>
using P = pair<T, U>;
using PL = P<ll, ll>;
using VPL = V<PL>;
template <typename T>
inline bool chmax(T& a, T b);
template <typename T>
inline bool chmin(T& a, T b);
void print_ints(vector<ll> v);
template <typename T>
void drop(T a);

const ll INF = 1e18;

void solve() {
  ll N;
  cin >> N;

  VL as(N);
  rep(i, N) cin >> as[i];

  ll min_v = *min_element(all(as));
  ll max_v = *max_element(all(as));

  const string Yes = "Yes";
  const string No = "No";

  // 種類数を A とする。
  // 自身の値は自身が唯一の種類であれば A-1、そうでなければ A となる。
  // よって、 A-1 と A のみしか出現しえないため、差が 2 以上であれば不可。

  ll diff = max_v - min_v;
  if (diff >= 2) drop(No);

  if (diff == 0) {
    // 上の議論より、全てが唯一の種類で値が A-1
    // であるか、全てが唯一でない種類かつ値が A のいずれか。

    // 前者の場合、種類数 A は N となる
    if (max_v == N - 1) drop(Yes);

    // 後者の場合、同じ種類のグループを A 個作れるかどうかで判定可能。
    // 最もグループを多くすると、各グループ 2 種類のみからなる floor(N/2)
    // となるから、これ以下場合のみ可能。
    if (max_v <= N / 2) drop(Yes);

    drop(No);
  } else if (diff == 1) {
    ll small_ct = 0;
    rep(i, N) if (as[i] == min_v)++ small_ct;

    ll large_ct = N - small_ct;

    // 小さい方は唯一の種類、大きい方は複数の種類となる。
    // 大きい方の種類数は [1, large_ct / 2] であるから、
    // small_ct + [1, large_ct / 2] に A が含まれていれば良い。

    if (small_ct + 1 <= max_v && max_v <= small_ct + large_ct / 2) drop(Yes);
    drop(No);
  }
}

struct exit_exception : public std::exception {
  const char* what() const throw() { return "Exited"; }
};

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

  try {
    solve();
  } catch (exit_exception& e) {
  }

  return 0;
}
#endif

template <typename T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}

template <typename T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}

void print_ints(vector<ll> v) {
  rep(i, v.size()) {
    if (i > 0) {
      cout << " ";
    }

    cout << v[i];
  }

  cout << endl;
}

template <typename T>
void drop(T res) {
  cout << res << endl;
  throw exit_exception();
}


Measured memory_bytes: 1024
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cassert>
#include <iostream>
#include <cctype>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <queue>
#include <set>
#include <stack>
#include <map>
#include <utility>
#include <numeric>
#include <algorithm>
#include <bitset>
#include <complex>
#include <fstream>
using namespace std;
typedef long long ll;
const double EPS = 1e-9;
typedef vector<int> vint;
typedef pair<int, int> pint;
#define rep(i, n) REP(i, 0, n)
#define ALL(v) v.begin(), v.end()
#define MSG(a) cout << #a << " " << a << endl;
#define REP(i, x, n) for(int i = x; i < n; i++)
template<class T> T RoundOff(T a){ return int(a+.5-(a<0)); }
template<class T, class C> void chmax(T& a, C b){ if(a < b) a = b; }
template<class T, class C> void chmin(T& a, C b){ if(b < a) a = b; }
template<class T, class C> pair<T, C> mp(T a, C b){ return make_pair(a, b); }

const int INF = 1 << 30;

int main()
{
    int w, n;
	int times = 0;
    while(cin >> w && w)
    {
		times++;
		cin >> n;

		vint now(w+1, 0), last(w+1, 0);

		rep(i, n)
		{
			int val, wei;
			char k;
			cin >> val >> k >> wei;

			rep(j, w+1)
				now[j] = (j < wei ? last[j] : max(last[j], last[j - wei] + val));

			last = now;
		}

		int rv = 0, rw = 0;
		rep(i, w + 1)
		{
			if(rv < last[i])
			{
				rv = last[i];
				rw = i;
			}
		}

		cout << "Case " << times << ":" << endl << rv << endl << rw << endl;
	}
}

Measured memory_bytes: 0
package main

import (
    "fmt"
    "bufio"
    "os"
)

//FOR I/O : STARTS
var Reader *bufio.Reader = bufio.NewReader(os.Stdin)
var Writer *bufio.Writer = bufio.NewWriter(os.Stdout)
func Printf (f string, a ...interface{}) { fmt.Fprintf(Writer, f, a...) }
func Scanf (f string, a ...interface{}) { fmt.Fscanf(Reader, f, a...) }
func Println (a ...interface{}) { fmt.Fprintln(Writer, a...)}
func Scanln (a ...interface{}) { fmt.Fscanln(Reader, a...)}
//I/O ENDS HERE

func Abs(x int) int {
    if x < 0 {
        return -x
    }
    return x
}

func Min(x, y int) int {
    if x < y {
        return x
    } else {
        return y
    }
}

func Max(x, y int) int {
    if x >= y {
        return x
    } else {
        return y
    }
}

func Ceil(x, y int64) int64 {
    //returns x/y
    if x%y == 0 {
        return x/y
    } else {
        return int64(x/y)+1
    }
}

func main() {
    defer Writer.Flush()

    var temp1, temp2, a, b, x int64
    Scanf("%d\n", &x)

    max_limit := int64(1000)

    for a = -max_limit; a <= max_limit; a += 1 {
        for b = -max_limit; b < a; b += 1 {
            temp1 = a*a*a*a*a
            temp2 = b*b*b*b*b

            if temp1 - temp2 == x {
                Printf("%d %d\n", a, b)
                return
            }
        }
    }
}


Measured memory_bytes: 1832
#include <iostream>
#include <string>
#include <vector>
#include <algorithm> 
#include <utility> 
#include <tuple> 
#include <cstdint> 
#include <cstdio> 
#include <map> 
#include <queue> 
#include <set> 
#include <stack> 
#include <deque> 
#include <unordered_map> 
#include <unordered_set> 
#include <bitset> 
#include <cctype> 
#include <cmath>
#include <iomanip>
#include <ctype.h>

using namespace std;
using ll = long long;
using vi = vector<int>;
using vvi = vector<vi >;
using vl = vector<ll>;
using vvl = vector<vl >;
using pairi = pair<int, int>;
using pairl = pair<ll, ll>;

#define TR ","
#define TS " "
#define rep(i,N) for(ll i=0;i<(ll)N;++i)
#define rpt(i,a,b) for(ll i=a;i<(ll)b;++i)
#define all(v) v.begin(), v.end()
#define IO ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)

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

ll lcm(ll x, ll y) {
    return x / gcd(x, y) * y;
}

void printVector(const vector<ll>& vec) {
    for (ll value : vec) {
        cout << value << " ";
    }
    cout << endl;
}

vector<int> IntegerToVector(int bit, int N) {
    vector<int> S;
    for (int i = 0; i < N; ++i) {
        if (bit & (1 << i)) {
            S.push_back(i);
        }
    }
    return S;
}

int main()
{
    int x; cin >> x;
    if (x == 0) { cout << 1 << endl; }
    else { cout << 0 << endl; }
}

Measured memory_bytes: 3592
#
# 　　  ⋀_⋀　 
#　　  (･ω･)  
# .／ Ｕ ∽ Ｕ＼
#  │＊　合　＊│
#  │＊　格　＊│ 
#  │＊　祈　＊│ 
#  │＊　願　＊│ 
#  │＊　　　＊│ 
#      ￣
#
import sys
input=sys.stdin.readline
from math import floor,ceil,sqrt,factorial,log #log2ないｙｐ
from heapq import heappop, heappush, heappushpop
from collections import Counter,defaultdict
from itertools import accumulate,permutations,combinations,product,combinations_with_replacement
from bisect import bisect_left,bisect_right
inf=float('inf')
mod = 10**9+7
def INT_(n): return int(n)-1
def MI(): return map(int,input().split())
def MF(): return map(float, input().split())
def MI_(): return map(INT_,input().split())
def LI(): return list(MI())
def LI_(): return [int(x) - 1 for x in input().split()]
def LF(): return list(MF())
def LIN(n:int): return [I() for _ in range(n)]
def LLIN(n: int): return [LI() for _ in range(n)]
def LLIN_(n: int): return [LI_() for _ in range(n)]
def LLI(): return [list(map(int, l.split() )) for l in input()]
def I(): return int(input())
def F(): return float(input())
def ST(): return input().replace('\n', '')
def main():
    S = ST()
    if S[0] == S[1] or S[1] == S[2] or S[2] == S[3]:
        print("Bad")
    else:
        print("Good")
if __name__ == '__main__':
    main()

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

namespace D
{
    class Solver
    {
        public void Solve()
        {
            int[] nm = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
            int n = nm[0];
            int m = nm[1];
            var min = Enumerable.Repeat(15 << 26, n + 1).ToArray();
            for (int i = 0; i < m; i++)
            {
                int[] ab = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
                min[ab[0]] = Math.Min(min[ab[0]], ab[1]);
            }
            int p = 1, ans = 0;
            for (int i = n - 1; i >= 1; i--)
            {
                min[i] = Math.Min(min[i], min[i + 1]);
            }
            while (p < n && min[p] <= n)
            {
                p = min[p];
                ans++;
            }
            Console.WriteLine(ans);
        }

    }

    class M
    {
        public static void Main(string[] args)
        {
            new Solver().Solve();
        }
    }

};


Measured memory_bytes: 18656
//***Faithless is he that says farewell when the road darkens***

#include<bits/stdc++.h>
using namespace std;

#define mp make_pair
#define mt make_tuple
#define fi first
#define se second
#define pb push_back
#define ll long long
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define rep(i,n) for(i=0;i<n;i++)
#define forn(i, n) for (ll i = 0; i < (ll)(n); ++i)
#define for1(i, n) for (ll i = 1; i <= (ll)(n); ++i)
#define ford(i, n) for (ll i = (ll)(n) - 1; i >= 0; --i)
#define fore(i, a, b) for (ll i = (ll)(a); i <= (ll)(b); ++i)
#define fora(it,x) for(auto it:x)
#define PI 3.14159265
#define sync ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define endl "\n"

typedef pair<ll, ll> pii;
typedef vector<ll> vi;
typedef vector<pii> vpi;
typedef vector<vi> vvi;
typedef long long i64;
typedef vector<i64> vi64;
typedef vector<vi64> vvi64;
typedef pair<i64, i64> pi64;
typedef long double ld;

template<class T> bool uin(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool uax(T &a, T b) { return a < b ? (a = b, true) : false; }

ll a[2*100002],b[2*100002];
int main()
{
    ll n;
    cin>>n;
    forn(i,n) cin>>a[i]>>b[i];
    sort(a,a+n);
    sort(b,b+n);
    ll p,q;
    if(n%2==0) p=a[n/2-1]+a[n/2];
    else p=a[n/2];
    if(n%2==0) q=b[n/2-1]+b[n/2];
    else q=b[n/2];
    cout<<(q-p+1);
}


Measured memory_bytes: 6768
from collections import Counter
N=int(input())
S=[]
for i in range(N):
    Si=input()
    S.append(Si)


counter=Counter(S)
L=[]
t=0
for j in range(N):
    value=counter[S[j]]
    if t<value:
        t=value
        L=[]
        L.append(S[j])
    
    elif t==value:
        L.append(S[j])
    
    elif t>value:
        pass

L=list(set(L))
L.sort()
for k in range(len(L)):
    print(L[k])

Measured memory_bytes: 45808
#include<bits/stdc++.h>
using namespace std;
int main()
{
  int i,j,k,n;
  cin>>n>>k;
  int a[n];
  for(i=0;i<n;i++)
    cin>>a[i];

vector<int>d(n,INT_MAX);
	d[0]=0;
	
	for(int i=1;i<n;i++){
	for(int j=i-1;j>=max(i-k,0);j--){
	d[i]=min(d[i],d[j]+abs(a[j]-a[i]));
    }}
    
  
  cout<<d[n-1];
  return 0;
}

Measured memory_bytes: 1024
N,K=map(int,input().split())
A=list(map(int,input().split()))

SUMA=[0]
for a in A:
    SUMA.append(SUMA[-1]+a)

SUM=[]
for i in range(1,N+1):
    for j in range(i,N+1):
        SUM.append(SUMA[j]-SUMA[i-1])

#print(SUM)
#SUM.sort()
#print(sorted(SUM))
#print([bin(SUM[i]) for i in range(len(SUM))])
#SUM.sort(reverse=True)

for i in range(40,-1,-1):
    COUNT=0
    for s in SUM:
        if (s & 1<<i)!=0:
            COUNT+=1

    #print(COUNT)#,SUM)

    if COUNT<K:
        continue
    else:
        NLIST=[]
        for s in SUM:
            if (s & 1<<i)!=0:
                NLIST.append(s)

        SUM=NLIST

    #print(SUM)

ANS=SUM[0]
for s in SUM:
    ANS=ANS & s

print(ANS)


Measured memory_bytes: 67324
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <sstream>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>

#define rep(i, n) for(int i = 0; i < n; i ++)
#define COUNT(i, n) for(int i = 1; i <= n; i ++)
#define ITER(c) __typeof((c).begin())
#define each(c, it) for(ITER(c) it =(c).begin(); it!=(c).end(); it++)
#define ALL(c) c.begin(), c.end()
#define mp make_pair
#define pb push_back
#define MEMSET(v, h) memset((v), h, sizeof(v))
 
using namespace std; 

typedef pair<int, int> pii;
typedef long long ll;
typedef vector<int> vi;
typedef vector<string> vs;

const int INF = 1 << 24;
const int N = 4001;
const int M = 1001;

int main(void){
    vector<vi> dp(5);
    rep(i, 5) dp[i].resize(N);
    dp[0][0] = 1;

    COUNT(i, 4) rep(j, N) if(dp[i - 1][j]) rep(k, M) dp[i][j + k] += dp[i - 1][j];

    for(int n; cin >> n; cout << dp[4][n] << endl);
 
    return 0;
}

Measured memory_bytes: 1276
#include<bits/stdc++.h>
#include<iostream>
#include<cstring>
#include<cmath>
#include<iomanip>
using namespace std;
char a1[2006811];
long long int n,i,j,m,sum,sumend,dr,a[2006811],ch,v[2006811],c[2006811],s1[2006811],s2[2006811],b,c1,k;
bool cmp(int a,int b)
{
    return a>b;
}
int gcd(int a,int b)
{
    if(!b)
        return a;
    return gcd(b,a%b);
}
long long int maxx(int a,int b)
{
    if(a>=b)
        return a;
    return b;
}
long double maxxx(long double a,long double b)
{
    if(a>=b)
        return a;
    return b;
}
long long int lhd(long long int a)
{
    if(a<=0)
        return -a;
    return a;
}
long long int lhdmin(long long int a,long long int b)
{
    if(a<=b)
        return a;
    return b;
}
long long int dcecs(long long int n)
{
    if(n<2)
        return 0;
    if(n==2)
        return 1;
    for(int i=3;i<=sqrt(n);i+=2)
        if(n%i==0)
            return 0;
    return 1;
}
bool gqt(int x,int y)
{
    if(x+y==-2)
        return 1;
    if(x!=-1&&y!=-1&&v[x]==v[y]&&gqt(s2[x],s1[y])&&gqt(s1[x],s2[y]))
        return 1;
    return 0;
}
void xjbs(int n)
{
    c[n]=1;
    if(s1[n]!=-1)
    {
        xjbs(s1[n]);
        c[n]+=c[s1[n]];
    }
    if(s2[n]!=-1)
    {
        xjbs(s2[n]);
        c[n]+=c[s2[n]];
    }	
}
long long int minnn(long long int a,long long int b)
{
    if(a<=b)
        return a;
    return b;
}
long long int gqt(long long int b,long long int p,long long int k)
{
    /*if(p==0)
        return 1;
    if(k==1)
        return 0;
    if(b%2==1)
        return gqt(b,p/2,k)%k*b%k*gqt(b,p/2,k)%k;
    else if(b%2==0)
        return gqt(b,p/2,k)%k*gqt(b,p/2,k)%k;*/
    long long int sum=1;
    while(p!=0)
    {
        if(p%2==1)
        {
            sum*=b;
            sum%=k;
        }
        b*=b;
        b%=k;	
        p/=2;
    }
    return sum;
}
const int k1=1e9+9;
string a11,a2;
long double dol=100.0,mark;
char charlsbl;
long long int la2,x1,x2,x3,x4,flag[205]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,20,19,18,17,16,15,14,13,12,11,10,9,8,7,6,5,4,3,2,1};
int main()
{
    cin>>n;
    for(i=0;i<n;i++)
    	cin>>a1[i];
    for(i=0;i<n;i++)
    {
    	
        if(a1[i]=='I')
        	sum++;
        	//continue;
        else
        	sum--;
        sumend=maxx(sumend,sum);
    }
    //sumend=sum;
    cout<<sumend<<endl;
    return 0;
}

Measured memory_bytes: 2304
#include <bits/stdc++.h>
#define LL long long
using namespace std;
 
const int maxn = 20;
int n, m, swaped[maxn];
bool used[maxn], ans;
 
string s[20];
 
bool check()
{
    memset(used, false, sizeof(used));
    for(int i = 0; i < m; i ++) {
        if(used[i])
            continue;
        for(int j = 0; j < m; j ++) {
            bool cur = true;
            if(i == j || used[j])
                continue;
            for(int k = 0; k < n; k ++) {
                if(s[swaped[k]][i] != s[k][j]) {
                    cur = false;
                    break;
                }
            }
            if(cur) {
                used[i] = used[j] = true;
                break;
            }
        }
    }
 
    int cnt = 0, noused = -1;
    for(int i = 0; i < m; i ++)
        if(!used[i])
            cnt ++, noused = i;
    if((cnt >= 2 ) || (cnt && (m % 2 == 0)))
        return false;
    for(int i = 0; i < n; i ++)
        if(s[swaped[i]][noused] != s[i][noused])
            return false;
    return true;
}
 
void dfs(int u, int flag)
{
    if(u == (n + 1) / 2) {
        if(check())
            ans = true;
        return;
    }
 
    for(int i = u; i < n; i ++) {
        if(swaped[i] == -1) {
            for(int j = i + 1; j < n; j ++) {
                if(swaped[j] >= 0)
                    continue;
 
                swaped[i] = j;
                swaped[j] = i;
                dfs(u + 1, flag);
                swaped[i] = swaped[j] = -1;
            }
            if(flag) {
                swaped[i] = i;
                dfs(u + 1, false);
                swaped[i] = -1; 
            }
            break;
        }
    }
}
 
int main()
{
    scanf("%d%d", &n, &m);
    memset(swaped, -1, sizeof(swaped));
    for(int i = 0; i < n; i ++)
        cin >> s[i];
 
    if(n & 1)
        dfs(0, true);
    else
        dfs(0, false);
    printf(ans ? "YES" : "NO");
    return 0;
}

Measured memory_bytes: 256
#include <iostream>
#include <set>
#include <stdint.h>
#include <utility>
#include <limits.h>

using namespace std;

int gcd( int m, int n )
{
  while( m != n ) {
    if ( m > n ) m = m - n;
    else         n = n - m;
  }

  return m;
}//gcd

int main()
{
  int64_t N, X;
  cin >> N >> X;

  set<int64_t> cities;
  cities.insert(0);
  int64_t min_diff = INT64_MAX;
  
  for (int n=0; n<N; ++n) {
    int64_t x;
    cin >> x;
    
    x -= X;
    if (x<0)
      x = -x;
    
    cities.insert(x);
    
    auto next = cities.upper_bound(x);
    if (next != cities.end()) {

      int64_t diff_next = *next - x;

      if (min_diff == INT64_MAX)
	min_diff = diff_next;
      else
	min_diff = gcd(diff_next, min_diff);
    }

    auto prev = cities.lower_bound(x);
    if (prev != cities.begin()) {
      --prev;
      
      int64_t diff_prev = x - *prev;

      if (min_diff == INT64_MAX)
	min_diff = diff_prev;
      else
	min_diff = gcd(diff_prev, min_diff);
    }

  }

  cout << min_diff << endl;
  
  return 0;
}


Measured memory_bytes: 4864
package main

import "fmt"

func main() {
	var n, y int
	fmt.Scan(&n, &y)

	for i := 0; i <= n; i++ {
		for j := 0; j <= (n - i); j++ {
			k := n - i - j
			if 10000*i+5000*j+1000*k == y {
				fmt.Println(i, j, k)
				return
			}
		}
	}
	fmt.Println("-1 -1 -1")
}


Measured memory_bytes: 512
#include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i = 0;i<n;i++)
#define erep(i,n) for(int i = 0;i<=n;i++)
#define rep1(i,n) for(int i = 1;i<n;i++)
#define erep1(i,n) for(int i = 1;i<=n;i++)
typedef long long ll;
#define vint vector<int>
#define vstring vector<string>
#define vll vector<ll>
#define vbool vector<bool>
#define INF 100000000

int main(){
  int n;
  cin >> n;
  vll march(5);
  rep(i,n){
    string s;
    cin >> s;
    if(s[0] == 'M') march[0]++;
    if(s[0] == 'A') march[1]++;
    if(s[0] == 'R') march[2]++;
    if(s[0] == 'C') march[3]++;
    if(s[0] == 'H') march[4]++;
  }
  ll ans = 0;
  for(int i = 0;i<3;i++){
    for(int j = i+1;j<4;j++){
      for(int s = j+1;s<5;s++){
        ans += march[i]*march[j]*march[s];
      }
    }
  }
  cout << ans << endl;
}

Measured memory_bytes: 256
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <stdint.h>
#include <queue>
#include <bitset>
#include <iomanip>
#include <set>
#include <map>

using namespace std;

#define PI (3.14159265358979323846)
#define INF (2147483647)
#define INF_LL (9223372036854775807)
#define DIV_NUM (1000000007)



int main() {

	int K, N;
	cin >> K >> N;
	vector<int> pos;
	for (int i = 0; i < N; i++) {
		int tmp;
		cin >> tmp;
		pos.push_back(tmp);
	}

	sort(pos.begin(), pos.end());

	vector<int> dist;
	for (int i = 0; i < N; i++) {
		int dis;
		if (i == N - 1) dis = K - pos[i] + pos[0];
		else dis = pos[i + 1] - pos[i];
		dist.push_back(dis);
	}

	sort(dist.begin(), dist.end(),greater<int>());

	int ans = K - dist[0];

	cout << ans << endl;

	return 0;

}

Measured memory_bytes: 2548
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <climits>
using namespace std;
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++ )
#define repf(i,m,n) for(int (i)=m;(i)<n;(i)++)




int main(){
    int n;
    int tmp=0;
    cin>>n;
    vector<int> v(n+1,0);
    rep(i,n) cin>>v[i];
    int ans=0;
    repf(i,1,101){
        rep(j,n+1){
            if(v[j]>=i){tmp=1;}
            else if(tmp==1){
                ans++;
                tmp=0;
            }
        }
    }
    cout<<ans<<endl;
    return 0;

}


Measured memory_bytes: 256
using System;

namespace AIZUJudge {
    class Disit {
        static void Main(string[] args) {
            while (true) {
                string data = Console.ReadLine();
                if (string.IsNullOrEmpty(data)) break;

                string[] tmp = data.Split(' ');
                int a = int.Parse(tmp[0]);
                int b = int.Parse(tmp[1]);

                int sum = a + b;
                int i = 1;
                while (true) {
                    if (sum < Math.Pow(10, i)) {
                        Console.WriteLine(i);
                        break;
                    }
                    i++;
                }
            }
       }
    }
}

Measured memory_bytes: 9484
#include<bits/stdc++.h>
using namespace std;
int main(){
  int ans=0,sum=0;
  string s;
  int a[10];
  cin>>s;
  for(int i=0;i<s.size();i++){
    a[i]=((int)s[i]-'0');
    sum+=a[i];
  }
  reverse(a,a+s.size());
  int temp=1;
  for(int i=0;i<s.size();i++){
    ans+=a[i]*temp;
    temp*=10;
  }
  if(ans%sum==0)cout<<"Yes"<<endl;
  else cout<<"No"<<endl;
  return(0);
}
  


Measured memory_bytes: 256
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }

/* attention
    long longのシフト演算には気をつけよう
    タイポした時のデバッグが死ぬほどきつくなるので変数名は最低3字くらい使った方がいいかも
    sizeは(int)とキャストしよう
    ごちゃごちゃ場合分けを考える前に全探索は考えましたか？
*/

const ll mod = 1e9+7;

void chmod(ll &M){
    if(M >= mod) M %= mod;
    else if(M < 0){
        M += (abs(M)/mod + 1)*mod;
        M %= mod;
    }
}

ll modpow(ll x, ll n){
    if(n == 0) return 1;

    ll res = modpow(x, n/2);
    if(n%2 == 0) return res*res%mod;
    else return res*res%mod*x%mod;
}

ll power(ll x, ll n){
    if(n == 0) return 1;

    ll res = power(x, n/2);
    if(n%2 == 0) return res*res;
    else return res*res*x;
}

int getl(int i, int N) { return i==0? N-1:i-1; };
int getr(int i, int N) { return i==N-1? 0:i+1; };

/* <--------------------------------------------> */


class UnionFind{
public:
    //親の番号を格納する。親だった場合はー（その集合のサイズ）
    vector<int> parents;

    //作る時はparentsを-1で初期化する
    //こうすることで全部ばらばらになる
    UnionFind(int n){
        parents = vector<int>(n, -1);
    }

    //Aがどのグループにいるか調べる
    int root(int A){
        if(parents[A]<0) return A;
        return parents[A] = root(parents[A]);
    }

    //自分のいるグループの大きさを調べる
    int size(int A){
        return -parents[root(A)];
    }

    //AとBをくっつける
    bool connect(int A, int B){
        //AとBを直接ではなく親同士をくっつける
        A=root(A);
        B=root(B);
        if(A==B){
            return false;
        }

        //大きい方（A)に小さい方（B)をくっつけたい
        if(size(A)<size(B)) swap(A, B);

        parents[A] += parents[B];
        parents[B] = A;

        return true;
    }
};

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

    int n, m; cin >> n >> m;
    vector<int> p(n+1), pos(n+1);

    for(int i=1; i<=n; ++i){
        cin >> p[i];
        pos[p[i]] = i;
    }

    UnionFind uni(n+1);
    for(int i=0; i<m; ++i){
        int x, y; cin >> x >> y;
        uni.connect(x, y);
    }

    int ans = 0;
    for(int i=1; i<=n; ++i){
        if(uni.root(pos[i]) == uni.root(i)) ++ans;
    }

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


Measured memory_bytes: 1408
// Author: Vamsi Krishna Reddy Satti
// With love for Competitive Programming!
 
#include <bits/stdc++.h>
using namespace std;
 
#define fast_io ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
#define cout_precision cout.setf(ios::fixed); cout.precision(32);
 
using ll = int64_t; using vll = vector<ll>; using vvll = vector<vll>;
using pll = pair<ll, ll>; using vpll = vector<pll>; using vvpll = vector<vpll>;
using ld = long double;
 
// ------------------------------------------------------------------------------------------------

const ll MOD = 1e9 + 7;
ll n, ans;

int main() {
    fast_io; cout_precision;
    cin >> n;
    ans = 1;
    for (ll i = 2; i <= n; i++) {
        (ans *= i) %= MOD;
    }
    cout << ans << endl;
}

Measured memory_bytes: 256
a, b, c, x, y = map(int, input().split())

if a+b<=2*c:
  print(x*a+y*b)
else:
  ans = c*2*min(x, y)
  if x>=y:
    if a<=2*c:
      ans += (x-y)*a
    else:
      ans += (x-y)*2*c
  else:
    if b<=2*c:
      ans += (y-x)*b
    else:
      ans += (y-x)*2*c
  print(ans)

Measured memory_bytes: 9188
#include <iostream>
#include <sstream>
#include <stdio.h>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <functional>
#include <vector>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <cassert>
#include <exception>
#include <numeric>
using namespace std;
typedef long long ll;
typedef string str;
typedef pair<ll, ll> Pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<char> vc;
typedef vector<str> vs;
typedef vector<Pll> vp;
typedef vector<bool> vb;
#define rep(i, a, n) for (ll i = (a); i < (n); ++i)
#define rrep(i, a, n) for (ll i = (a); i > (n); --i)
#define erep(i, a, n) for (ll i = (a); i <= (n); ++i)
#define rerep(i, a, n) for (ll i = (a); i >= (n); --i)
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define mp make_pair
#define sz(x) ((int)x.size())
#define vec_max(V) *max_element(all(V))
#define vec_min(V) *min_element(all(V))
#define vec_sum(V) accumulate(all(V), 0LL)
#define print(X) cout << (X) << "\n"
#define _ << " " <<
#define Yes print("Yes")
#define No print("No")
static const int INF = 1e+9+7;

int main(){
  vll A(5);
  rep(i,0,5) cin >> A[i];
  ll min = 10;
  ll index = 0;

  rep(i,0,5){
    if(A[i] % 10 < A[index] % 10 && A[i] % 10 != 0){
      index = i;
    }
  }

  ll sum = 0;
  rep(i,0,5){
    if(i != index){
      if(A[i]%10 != 0){
        A[i] = (int(A[i]/10)+1) * 10;
      }
      sum += A[i];
    }
  }

  print(sum + A[index]);

 return 0;
}


Measured memory_bytes: 256
//
//  main.cpp
//  zero
//
//  Created by 叶金炜 on 2019/4/2.
//  Copyright © 2019 okstal. All rights reserved.
//

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <string.h>
#define pi acos(-1)
using namespace std;
int main()
{
    char c[57];
    int n=1,x,y,z;
    while (cin>>x>>y>>z)
    {
        if(x==-1&&y==-1&&z==-1)break;
        else if(x==-1||y==-1)c[n]='F';
        else if(x+y>=80)c[n]='A';
        else if(x+y>=65&&x+y<80)c[n]='B';
        else if(x+y>=50&&x+y<65)c[n]='C';
        else if(x+y>=30&&x+y<50)
        {
            if(z>=50)c[n]='C';
            else c[n]='D';
        }
        else if(x+y<40)c[n]='F';
        n++;
    }
    for(int i=1;i<=n-1;i++)cout<<c[i]<<endl;
    return 0;
}



Measured memory_bytes: 3096
def resolve():
    # 整数 1 つ
    # n = int(input())
    # 整数複数個
    # a, b = map(int, input().split())
    # 整数 N 個 (改行区切り)
    # N = [int(input()) for i in range(N)]
    # 整数 N 個 (スペース区切り)
    # N = list(map(int, input().split()))
    # 整数 (縦 H 横 W の行列)
    A = [list(map(int, input().split())) for i in range(3)]

    B = []
    for i in range(3):
        C = []
        for j in range(3):
            C.append(A[i][j] - min(A[i]))
        B.append(C)

    flag = True
    for i in range(3):
        if B[0][i] != B[1][i] or B[0][i] != B[2][i]:
            flag = False

    if flag == True:
        print("Yes")
    else:
        print("No")
resolve()

Measured memory_bytes: 39792