jiahuimbzuai/CoQuIR huggingface dataset:
//  [swift]
import Foundation

#if swift(>=4.0)
extension String {
    func split(by separator: String) -> [String] {
        return self.components(separatedBy: separator)
    }
    func toArray() -> [String] {
        return self.map{String($0)}
    }
}
func exponentiate(_ lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#else
extension String {
    func split(by separator: String) -> [String] {
        return self.componentsSeparatedByString(separator)
    }
    var count: Int {
        return self.characters.count
    }
    func toArray() -> [String] {
        return self.characters.map{String($0)}
    }
    func uppercased() -> String {
        return self.uppercaseString
    }
    func lowercased() -> String {
        return self.lowercaseString
    }
}
//extension Array where Element == String {
//    func joined(separator separator: String) -> String {
//        return self.joinWithSeparator(separator)
//    }
//}
extension Array where Element: Comparable {
    func max() -> Element {
        return self.maxElement()!
    }
    func min() -> Element {
        return self.minElement()!
    }
    func sorted() -> Array {
        return self.sort()
    }
    func reversed() -> Array {
        return self.reverse()
    }
    mutating func sort() {
        self.sortInPlace()
    }
}
extension Array {
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
func stride<T: Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> {
    return start.stride(to: end, by: stride)
}
func exponentiate(lhs: Int, _ rhs: Int) -> Int {
    return (0..<rhs).reduce(1){i,_ in i*lhs}
}
#endif
func readInt() -> Int? {
    return Int(readLine()!)
}
func readStringSplit(by separator: String) -> [String] {
    return readLine()!.split(by: separator)
}
func readIntSplit(by separator: String) -> [Int] {
    return readLine()!.split(by: separator).map{Int($0)!}
}

/*************** テストスペース ***************/



/*************** メインプログラム ***************/

let N = readInt()!
let T = readIntSplit(by: " ")
let M = readInt()!
let drink = (0..<M).map{_ in readIntSplit(by: " ")}

for i in 0..<M {
    var tmp = T
    tmp[drink[i][0]-1] = drink[i][1]
    print(tmp.reduce(0){$0+$1})
}
//  [swift]

extension String: CollectionType {
    static func getValues(separator: Character = " ") -> [String] {
        return readLine()!.split(separator)
    }
}

typealias PX = (P: Int, X: Int)

let N = Int(String.getValues()[0])
let T = String.getValues().map {Int($0)!}
let M = Int(String.getValues()[0])!

var PXs = [PX]()
(0 ..< M).forEach { i in
    let values = String.getValues()
    let P = Int(values[0])!
    let X = Int(values[1])!
    PXs.append(PX(P, X))
}

let sum = T.reduce(0) { value, current -> Int in
    value + current
}

let results = PXs.map { px -> Int in
    let diff = px.X - T[px.P - 1]
    return sum + diff
}

results.forEach { r in
    print(r)
}
//  [typescript]
"use strict";

const Main = args => {
  const input = args.trim().split("\n");
  const N = parseInt(input[0]);
  const T_arg = input[1].split(" ").map(e => parseInt(e));
  const M = parseInt(input[2]);
  const drink_arg = input.slice(3).map(e => e.split(' ').map(e => parseInt(e)));
  const result = drink_arg.map(e => {
    const P = e[0];
    const X = e[1];
    return T_arg.reduce((prev, curr, i) => {
      if (i === P - 1) {
        return prev + X;
      } else {
        return prev + curr;
      }
    }, 0);
  })
  console.log(result.join('\n'));
}

Main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin','utf8').split(/[\s]/);let input_i=-1;const tn=():number=>{input_i++;return Number(input[input_i])};const tnn=(n:number):number[]=>{const a=[];for(let i=0;i<n;i++){a.push(tn())}return a};const ts=():string=>{input_i++;return String(input[input_i])};const tss=(n:number):string[]=>{const a=[];for(let i=0;i<n;i++){a.push(ts())}return a};const to=(...arg)=>{console.log(...arg)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const floor=(a)=>{return Math.floor(a)};const asc=(ar:number[])=>{const t=[...ar];return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{const t=[...ar];return t.sort((a,b)=>{return b-a})};const sw=(a,arr:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<arr.length-1;i+=2){if(eval(a+op+arr[i])){return arr[i+1]}}return arr[arr.length-1]};const near=(n:number,arr:number[]):number=>{let ne=arr[0],ni=0;for(let i=1;i<arr.length;i++){if(Math.abs(n-ne)>Math.abs(n-arr[i])){ne=arr[i];ni=i}}return ni};const deduplicate=(a:any[]):any[]=>{return Array.from(new Set(a))}
const main=()=>{
  let n=tn(),t=tnn(n),m=tn()
  for(let i=0;i<m;i++){
    let tt=[...t],a=0
    tt[tn()-1]=tn()
    for(let i=0;i<n;i++){
      a+=tt[i]
    }
    to(a)
  }
}
main()
//  [typescript]
function main (input) {
  input = input.trim().split("\n");
  const n = Number(input[0]);
  const t = input[1].split(" ").map(n => Number(n));
  const m = Number(input[2]);
  const px = input.slice(3).map(n => n.split(" ").map(m => Number(m));
  const sum = t.reduce((a, b) => a + b));
  for (let i = 0; i < m; i++) {
    const [p, x] = px[i];
    console.log(sum - t[p-1] + x);
  }
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [typescript]
const main = (txt: any): void => {
  const input = txt.split('\n')
  for (let i = 3; i <= parseInt(input[2]) + 2; i++) {
    let T: number[] = input[1].split(' ').map((i: string) => parseInt(i))
    const [p, x] = input[i].split(' ').map((i: string) => parseInt(i))
    T[p - 1] = x
    console.log(T.reduce((a, b) => a + b))
  }
}



main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const T = input[1].map(Number);
  const M = Number(input[2][0]);

  const total = T.reduce((acc, cur) => acc + cur);
  const answer: number[] = [];

  for (let i = 3; i < M + 3; i++) {
    const [P, X] = input[i].map(Number);

    answer.push(total - (T[P - 1] - X));
  }

  return answer.join("\n");
};

console.log(main(read()));
//  [python]
n = input()
a = [int(x) for x in input().strip().split()]
count = {}
for x in a:
    if x not in count:
        count[x] = 0
    count[x] += 1
sort_keys = sorted(list(count.keys()), reverse=True)

result = 0
position = []
for idx, current in enumerate(sort_keys):
    value = count[current]
    if idx == 0:
        result += current * (value - 1)
        position.append([current, value])
    else:
        new_pos = 0
        while len(position) > 0 and value > 0:
            if position[0][1] > value:
                result += position[0][0] * value
                new_pos += value * 2
                position[0][1] -= value
                value = 0
            else:
                result += position[0][1] * position[0][0]
                new_pos += position[0][1] * 2
                value -= position[0][1]
                position.remove(position[0])
        if value > 0:
            new_pos += value
            result += current * value
        position.append([current, new_pos])
print(result)
//  [python]
import queue
import numpy as np
n = int(input())
aa = list(map(int, input().split()))
aa.sort(reverse=True)
aa = np.array(aa, dtype=int)*-1
q = queue.PriorityQueue()
q.put(aa[0])
cnt = 0
for i in aa[1:]:
    cnt += q.get()
    q.put(i)
    q.put(i)

print(-cnt)
//  [python]
# -*- coding: utf-8 -*-
import sys
import math
from bisect import bisect_left
from bisect import bisect_right
from collections import defaultdict
from heapq import heappop, heappush
import itertools
import random
from collections import deque
from decimal import *
import queue

input = sys.stdin.readline

def inputInt(): return int(input())
def inputMap(): return map(int, input().split())
def inputList(): return list(map(int, input().split()))
def inputStr(): return input()[:-1]

inf = float('inf')
mod = 1000000007

#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-

def main():
	N = inputInt()
	A = inputList()

	A.sort()
	A = A[::-1]
	ans = 0
	maxs = 0
	cnt = 0
	fst = True

	ansans = []
	pgt = queue.Queue()
	for i,val in enumerate(A):
		if i == 0:
			pgt.put(val)
		else:
			tmp = pgt.get()
			ansans.append(tmp)

			pgt.put(val)

			if tmp == val:
				pgt.put(val)
			else:
				pgt.put(val)

	#print(ansans)
	print(sum(ansans))


#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
#-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-
if __name__ == "__main__":
	main()
//  [java]
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;

public class Main {

  public static void main(String[] args) {
    resolve(System.in, System.out);
  }

  static void resolve(InputStream is, PrintStream pw) {
    Scanner sc = new Scanner(is);
    int n = Integer.parseInt(sc.next());
    int[] a = new int[n];
    int[] descendingOrder = new int[n];
    for (int i = 0; i < n; i++) {
      a[i] = Integer.parseInt(sc.next());
    }
    Arrays.sort(a);
    for (int i = 0; i < n; i++) {
      descendingOrder[i] = a[n - i - 1];
    }
    if (n == 2) {
      pw.println(descendingOrder[0]);
      return;
    }
    SortedSet<Pair> pairs = new TreeSet<>(
      Comparator
        .comparingInt(Pair::min)
        .thenComparingInt(p -> p.a)
        .thenComparingInt(p -> p.b)
        .reversed()
        .thenComparingInt(p -> p.id)
    );
    long ans = 0;
    Pair.resetCount();
    Pair first = new Pair(descendingOrder[0], descendingOrder[1]);
    pairs.add(first);
    pairs.add(new Pair(first));
    ans += descendingOrder[0];
    for (int i = 2; i < n; i++) {
      Iterator<Pair> targetIterator = pairs.iterator();
      Pair target = targetIterator.next();
      targetIterator.remove();
      ans += target.min();
      Pair[] split = target.split(descendingOrder[i]);
      pairs.add(split[0]);
      pairs.add(split[1]);
    }
    pw.println(ans);
  }

  static class Pair {

    static AtomicInteger counter = new AtomicInteger(0);

    int id = counter.getAndIncrement();

    int a;
    int b;

    public Pair(int a, int b) {
      this.a = a;
      this.b = b;
    }

    public Pair(Pair copy) {
      this(copy.a, copy.b);
    }

    int min() {
      return Math.min(a, b);
    }

    public Pair[] split(int c) {
      return new Pair[]{
        new Pair(a, c),
        new Pair(b, c)
      };
    }

    @Override
    public String toString() {
      return "Pair{" +
        "id=" + id +
        ", a=" + a +
        ", b=" + b +
        '}';
    }

    static void resetCount() {
      counter.set(0);
    }
  }
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;

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

long long MOD = 1000000000 + 7;

int main(){
  cout << setprecision(10);
  int N; cin >> N;

  vector<ll> A(N);
  for(int i = 0; i < N; i++){
    cin >> A[i] ;
  }
  sort(A.rbegin(), A.rend());

  int index = 0;
  bool flg = true;
  ll ans = 0;
  for(int i = 0; i < N; i++){
    if(i == 0) continue;
    if(i == 1) {
      ans += A[0];
      index++;
    } else { 
      if(flg){
        ans += A[index];
        flg = false;
      } else { 
        ans += A[index];
        flg = true;
        index++;
      }
    }
    cerr << "i: " << i << " index: " << index << " A: " << A[index] << endl;
  }
  cout << ans << endl;
  
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
 
int main() {
int N;
  long long result = 0;
  cin >> N;
    vector<int> A(N);
  vector<int> B = {};
  for(int a = 0;a < N;a++)cin >> A[a];
  sort(A.begin(),A.end());
  B.push_back(A[N-1]);
  for(int a = N-2;a >= 0;a--){
    result += B[0];
    B.erase(B.begin()); 
    B.push_back(A[a]);
    B.push_back(A[a]);
    
  }
  cout << result << endl;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;

int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);	
	int n;
	cin >> n;
	long long int sum = 0;
	vector <int> a(n);
	for (int i = 0; i < n; ++i){
		cin >> a[i];
	}
	sort(a.rbegin(),a.rend());
	sum += a[0];
	a.erase(a.begin());
	n-=2;
	while (n>=2){
		sum += *a.begin()*2;
		a.erase(a.begin());
		n -= 2;
	}
	if (n) sum += *a.begin();
	cout << sum << "\n";
	return 0;
}
//  [c]
#include<stdio.h>
int R=1,C=1,H[2000010],N[2000010];
//評価関数（いまはMIN）
int hyouka(int a,int b){
  if(C<b)return 1;
  if(C<a||b==0)return 0;
  return N[H[a]]>N[H[b]]?1:0;
}
//挿入関数
void hin(int a){
  int i=C++;
  for(N[H[0]=R]=a;hyouka(0,i/2);i/=2)H[i]=H[i/2];
  H[i]=R++;
}
//取り出す関数
int hout(){
  int rt=H[1],i,j=2,k=H[--C];
  for(i=1;hyouka(i,C);i=j)H[i]=H[j=i*2+1-hyouka(i*2,i*2+1)];
  H[j/2]=k;
  return rt;
}
int main(){
  long long n,d[200010],a,i,s=0;
  scanf("%lld",&n);
  for(i=0;i<n;i++){
    scanf("%lld",&a);
    hin(a);
  }
  for(i=0;i<n;i++)d[i]=N[hout()];
  R=C=1;
  hin(d[0]);
  for(i=1;i<n;i++){
    s+=N[hout()];
    hin(d[i]);
    hin(d[i]);
  }
  printf("%lld\n",s);
  return 0;
}
//  [c]
#include<stdio.h>
void push(long int x[],long int i,long int k){//最大が根になる x: 配列，i:push後のデータ数，k: pushするデータ
  x[i]=k;
  for(int j=i;j>1;j/=2)if(x[j]>x[j/2])x[j]^=x[j/2]^=x[j]^=x[j/2];
}
long int pop(long int x[],long int i){//最大値を取り出す x: 配列，i:pop前のデータ数
  int j=1,k;
  x[0]=x[1];x[1]=x[i];
  while(j*2<i&&(x[j*2]>x[j]||x[j*2+1]>x[j])){
    k=x[j*2]>x[j*2+1]?j*2:j*2+1;
    x[j]^=x[k]^=x[j]^=x[k];
    j=k;
  }
  return x[0];
}
void quicksort(long int a[],int s,int t){
  if(s<t){
    long int i=s,j=t,p=a[(s+t)/2];
    while(1){
      while(a[i]>p)i++;
      while(p>a[j])j--;
      if(i>=j)break;
      a[i]^=a[j]^=a[i]^=a[j];
      i++;j--;
    }
    quicksort(a,s,i-1);quicksort(a,j+1,t);
  }
}
int main(){
  long int a[200000],n,h[200001],i,r=0;
  scanf("%ld",&n);
  for(i=0;i<n;i++)scanf("%ld",&a[i]);
  quicksort(a,0,n-1);
  h[1]=a[0];
  for(i=1;i<n;i++){r+=pop(h,i);push(h,i,a[i]);push(h,i+1,a[i]);}
  printf("%ld",r);
}
//  [javascript]
'use strict';
const fs = require('fs');
const mod = BigInt(1e9+7);

function sum(...a) {
  var s = 0;
  for (var x of a) s += x;
  return s;
}


class ABC041 {
  static A(input) {
    var s, i
    input = input.trim().split('\n');
    [s, i] = input;
    i = parseInt(i, 10);
    console.log(s[i-1]);
  }
  static B(input) {
    var a, b, c;
    input = input.trim().split(' ').map(BigInt);
    [a, b, c] = input;
    var ans = a * b % mod * c % mod;
    ans = Number(ans);
    console.log(ans);
  }
  static C(input) {
    var [n, height] = input.trim().split('\n');
    height = height.split(' ').map(n => parseInt(n, 10));
    n = parseInt(n, 10);
    var height = Object.keys(height).map(key => [parseInt(key, 10)+1, height[key]]);
    height.sort((a, b) => b[1]-a[1]);
    for (var [i, _] of height) {console.log(i);}
  }
  static D(input) {
    var lines = input.trim().split('\n');
    var [n, m] = lines[0].split(' ').map(x => +x);
    var edges = new Array(n).fill(0);
    for (var i = 0; i < m; i++) {
      var [x, y] = lines[1+i].split(' ').map(x => +x);
      edges[x-1] |= 1<<(y-1);
    }
    var comb = new Array(1<<n).fill(null); comb[0] = 1;
    function count(edges, bit) {
      if (comb[bit] != null) {return comb[bit];}
      comb[bit] = 0;
      for (var i = 0; i < n; i++) {
        if (bit>>i&1 && !edges[i]) {
          var nxt_bit = bit & ~(1<<i);
          var nxt_edges = edges.slice();
          for (var j = 0; j < n; j++) {
            nxt_edges[j] &= ~(1<<i);
          }
          comb[bit] += count(nxt_edges, nxt_bit);
        }
      }
      return comb[bit];
    }
    console.log(count(edges, (1<<n)-1));
  }
}

class ABC173 {
  static A(input) {
    var n = +input.trim();
    console.log(Math.floor((n+999)/1000)*1000 - n);
  }
  static B(input) {
    var lines = input.trim().split('\n');
    var n = +lines[0];
    var cnt = {
      'AC': 0,
      'WA': 0,
      'TLE': 0,
      'RE': 0
    }
    for (var i = 0; i < n; i++) {
      cnt[lines[1+i]]++;
    }
    for (var [verd, c] of Object.entries(cnt)) {
      console.log(`${verd} x ${c}`);
    }
  }
  static C(input) {
    var lines = input.trim().split('\n');
    var [h, w, k] = lines[0].split(' ').map(x => +x);
    var c = lines.slice(1);
    var tot = 0;
    for (var i = 0; i < (1<<h); i++) {
      for (var j = 0; j < (1<<w); j++) {
        var cnt = 0;
        for (var y = 0; y < h; y++) {
          if (i>>y&1) continue;
          for (var x = 0; x < w; x++) {
            cnt += c[y][x]=='#' && !(j>>x&1);
          }
        }
        tot += cnt == k;
      }
    }
    console.log(tot);
  }
  static D(input) {
    var lines = input.trim().split('\n');
    var n = +lines[0];
    var a = lines[1].split(' ').map(x => +x);
    a.sort((a, b) => b-a);
    var m = Math.floor((n-2)/2);
    var s = a[0] + sum(...a.slice(1, 1+m))*2 + (n&1)*a[1+m];
    console.log(s);
  }
  static E(input) {
  }
  static F(input) {
  }
}


var input = fs.readFileSync('/dev/stdin', 'utf8');
ABC173.D(input);
//  [go]
package main

import (
	"fmt"
	"sort"
)


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

	a := make([]int,n )
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Sort( sort.Reverse(sort.IntSlice(a)))
	ans := 0
	t := n -1 // 何回足せるか
	for i := 0; i < n; i++ {
		lim := 2
		if i == 0 {
			lim = 1
		}
		for j := 0; j < lim; j++ {
			if t > 0 {
				ans += a[i]
				t--
			}
		}
	}

	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var n int

	fmt.Scan(&n)
	a := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&a[i])
	}
	sort.Sort(sort.Reverse(sort.IntSlice(a)))

	ans := a[0]
	c := 1
	for i := 1; i < n-1; i++ {
		ans += a[c]
		if i%2 == 0 {
			c++
		}
	}

	fmt.Println(ans)
}
//  [go]
package main

import (
	"fmt"
	"sort"
)

func main() {
	var N int
	fmt.Scan(&N)
	arr := make([]int, N)
	for i := range arr {
		fmt.Scan(&arr[i])
	}
	sort.Ints(arr)
	sum := arr[N-1]
	need := N - 2

	for i := N - 2; need > 0; i-- {
		if need > 1 {
			sum += arr[i] * 2
			need -= 2
		} else {
			sum += arr[i]
			need--
		}
	}
	fmt.Printf("%d\n", sum)
}
//  [ruby]
N = gets.to_i
A = gets.split.map(&:to_i)
A.sort_by!{|i|-i}
r = [A.shift] * 2
c = 0
until A.empty?
    (r.size - 1).times{|i|
        break if A.empty?
        r[i * 2 + 1, 0] = A.shift
        c += [r[i * 2], r[i * 2 + 2]].min
    }
end
warn r.inspect
puts c
//  [ruby]
class PriorityQueue
  def initialize(array = [])
    @data = []
    array.each{|a| add(a)}
  end

  def add(element)
    @data.push(element)
    bottom_up
  end

  def peek
    @data[0]
  end

  def poll
    if size == 0
      return nil
    elsif size == 1
      return @data.pop
    else
      min = @data[0]
      @data[0] = @data.pop
      top_down
      return min
    end
  end

  def size
    @data.size
  end

  private

  def swap(i, j)
    @data[i], @data[j] = @data[j], @data[i]
  end

  def bottom_up
    idx = size - 1
    while(has_parent?(idx))
      parent_idx = parent_idx(idx)
      if @data[parent_idx][:key] > @data[idx][:key]
        swap(parent_idx, idx)
        idx = parent_idx
      else
        return
      end
    end
  end

  def top_down
    idx = 0
    while (has_child?(idx))
      a = left_child_idx(idx)
      b = right_child_idx(idx)
      if @data[b].nil?
        c = a
      else
        c = @data[a][:key] <= @data[b][:key] ? a : b
      end
      if @data[idx][:key] > @data[c][:key]
        swap(idx, c)
        idx = c
      else
        return
      end
    end
  end

  def parent_idx(idx)
    (idx - (idx.even? ? 2 : 1)) / 2
  end

  def left_child_idx(idx)
    (idx * 2) + 1
  end

  def right_child_idx(idx)
    (idx * 2) + 2
  end

  def has_child?(idx)
    ((idx * 2) + 1) < @data.size
  end

  def has_parent?(idx)
    idx > 0
  end
end

N = gets.to_i
A = gets.split.map(&:to_i)

sorted = A.sort_by{ |v| -v }
comb = PriorityQueue.new([{ key: -sorted[1], value: [sorted[0],sorted[1]]}] * 2)

ans = sorted[0]
sorted[2..-1].each do |v|
  tmp = comb.poll
  ans += -tmp[:key]
  comb.add({ key: -v, value: [v, tmp[0]] })
  comb.add({ key: -v, value: [v, tmp[1]] })
end

puts ans
//  [ruby]
# ruby 2.7 + numo/ndarray
require "numo/narray"

class PriorityQueue
  attr_accessor :heap, :size
  def initialize(n)
    @heap = Numo::Int64.zeros(n)
    @size = 0
  end

  def <<(x)
    i = size
    self.size += 1
    while i > 0
      j = (i - 1) / 2
      break if heap[j] >= x # <
      heap[i] = heap[j]
      i = j
    end
    heap[i] = x
  end

  def pop
    ret = heap[0]
    self.size -= 1
    x = heap[size]
    i = 0
    while i * 2 + 1 < size
      a = i * 2 + 1
      b = i * 2 + 2
      a = b if b < size && heap[b] > heap[a] # <
      break if heap[a] <= x #<
      heap[i] = heap[a]
      i = a
    end
    heap[i] = x
    ret
  end
end

class Problem
  attr_accessor :a, :b, :c, :n, :m, :k, :h, :w, :x, :y, :ans, :q
  def initialize
    @n = gets.to_s.to_i
    @a = gets.to_s.split.map{ |v| v.to_i }.sort!.reverse!
    @q = PriorityQueue.new(200_000)
    v = a.shift
    q << v
  end

  def solve
    ans = 0
    while a.size > 0
      v = a.shift
      t = q.pop
      ans += t
      q << v
      q << v
    end
    puts ans
  end
end

pb = Problem.new
pb.solve
//  [rust]
use proconio::input;

fn main() {
    input! {
        n: usize,
        mut a: [i128; n],
    }

    a.sort();
    a.reverse();
    let mut sum = a[0];
    let mut t = n - 2;
    for i in 1..n {
        let lim = 2;
        for _ in 0..lim {
            if t > 0 {
                sum += a[i];
                t -= 1;
            }
        }
    }
    println!("{}", sum);
}
//  [rust]
use proconio::input;

fn main() {
  input! {
      n: usize,
      mut arr: [u64; n]
  }

  arr.sort();
  if arr.len() == 2 {
    println!("{}", arr[1]);
    return
  }

  if arr.len() == 3 {
    println!("{}", arr[1] + arr[2]);
    return
  }

  let mut result = arr.pop().unwrap();
  let mut base_stack: Vec<u64> = vec![arr.pop().unwrap()];
  while (0 <= arr.len()) {
    let mut stack: Vec<u64> = vec![];
    while 0 < base_stack.len() {
      let val = base_stack.remove(0);
      if arr.len() == 0 {
        println!("{}", result);
        return
      }
      stack.push(arr.pop().unwrap());
      result += val;

      if arr.len() == 0 {
        println!("{}", result);
        return
      }
      stack.push(arr.pop().unwrap());
      result += val;
    }
    base_stack = stack;
  }

  println!("{}", result);
}
//  [swift]
func readIntArray() -> [Int] {
    readLine()!.split(separator: " ").map({Int($0)!})
}

let N = Int(readLine()!)!
var A = readIntArray()
A.sort(by: {$0 > $1})

var ans = 0

for i in 1..<N {
    ans += A[i / 2]
}
print(ans)
//  [swift]
let N = Int(readLine()!)!
var As: [Int] = readLine()!.split(separator: " ").map { Int($0)! }
As.sort(by: >)

var res: Int = As[0]

for i in 0 ..< N - 2 {
    res += As[1 + i / 2]
}
print(res)  // (๑•ૅㅁ•๑)
//  [swift]
indirect enum BinaryTree {
    case node(BinaryTree, Int, BinaryTree)
    case empty

    init(array: [Int]) {
        guard !array.isEmpty else {
            self = .empty
            return
        }

        self = .node(
            .init(array: array, index: 1, depth: 1),
            array[0],
            .init(array: array, index: 2, depth: 1)
        )
    }

    private init(array: [Int], index: Int, depth: Int) {
        if index >= array.count {
            self = .empty
            return
        }
        self = .node(
            .init(array: array, index: index * 2 + 1, depth: depth+1),
            array[index],
            .init(array: array, index: index * 2 + 2, depth: depth+1)
        )
    }

    func count() -> Int {
        switch self {
        case .node(let left, let value, let right):
            var count = 0
            if case .node = left {
                count += value + left.count()
            }
            if case .node = right {
                count += value + right.count()
            }
            return count
        case .empty:
            return 0
        }
    }
 }

let n = readLine()!
var AN = readLine()!.split(separator: " ").compactMap { Int($0) }.sorted(by: { $0 > $1 })
let first = AN[0]
AN.removeFirst()
let binaryTree = BinaryTree(array: AN)
print(first + binaryTree.count())
//  [python]
N = int(input())

if N <= 999:
    print('ABC')
else:
    print('ABD')
//  [python]
n=int(input())
x=n-999 if n>999 else n
if n>999:
    print("ABD")
else:
    print("ABC")
//  [python]
N = int(input())
print("ABC" if N < 1000 else "ABD")
//  [python]
import numpy as np
N =int(input())
K=''
if N > 999:
    K='ABD'
else:
    K='ABC'
print(K)
//  [python]
import numpy as np

n = int(input())

if n<1000:
    print("ABC")
else:
    print("ABD")
//  [python]
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product


def read_int():
    return int(input())


def read_int_n():
    return list(map(int, input().split()))


def read_float():
    return float(input())


def read_float_n():
    return list(map(float, input().split()))


def read_str():
    return input()


def read_str_n():
    return list(map(str, input().split()))


def error_print(*args):
    print(*args, file=sys.stderr)


def mt(f):
    import time

    def wrap(*args, **kwargs):
        s = time.time()
        ret = f(*args, **kwargs)
        e = time.time()

        error_print(e - s, 'sec')
        return ret

    return wrap


@mt
def slv(N, AB):
    ans = 0
    return ans


def main():
    N = read_int()
    if N > 999:
        print('ABD')
    else:
        print('ABC')


if __name__ == '__main__':
    main()
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {
    public static void main(String[] args) throws Exception {
        String line = readLine();
        StringTokenizer st = new StringTokenizer(line, " ");
        Integer n = Integer.parseInt(st.nextToken());	/* 胃袋耐久期間 */
//        Integer a = Integer.parseInt(st.nextToken());	/* 賞味期限期間 */
//        Integer b = Integer.parseInt(st.nextToken());	/* 購入してから食べた日まで */

        /* 賞味期限までに食べた場合 */
        if ( n > 999) {
        	System.out.println("ABD");

        /* 胃袋耐久期間中に食べた場合 */
//        }else if ( (a + x) >= b) {
//        	System.out.println("safe");

        /* 胃袋耐久期間を超えて食べた場合 */
        }else {
        	System.out.println("ABC");
        }

    }

    private static String readLine() throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        return br.readLine();
    }
}
//  [java]
import java.io.IOException;
import java.util.NoSuchElementException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws IOException {
        try (
            BufferedReader reader = new BufferedReader(
                new InputStreamReader(System.in))) {
            final String s = reader.readLine();

            int N = Integer.parseInt(s);

            System.out.println(N < 1000 ? "ABC" : "ABD");
        }
    }
}
//  [java]
import java.io.*;

class Main {
        public static void main(String[] args) throws IOException {
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                int n = Integer.parseInt(br.readLine());
                
                if(n < 1000)
                        System.out.println("ABC");
                else
                        System.out.println("ABD");
        }
}
//  [java]
import java.io.*;
import java.util.*;

import static java.lang.Math.*;

public class Main {

    void solve() throws IOException {
        int n = readInt();
        if (n < 1000) {
            System.out.println("ABC");
        } else {
            System.out.println("ABD");
        }
    }

    //-------------------------------------------------

    final boolean ONLINE_JUDGE = !new File("input.txt").exists();

    BufferedReader in;
    PrintWriter out;
    StringTokenizer tok;

    public void run() {
        Runnable run = () -> {
            try {
                long startTime = System.currentTimeMillis();
                Locale.setDefault(Locale.US);
                if (ONLINE_JUDGE) {
                    in = new BufferedReader(new InputStreamReader(System.in));
                    out = new PrintWriter(System.out);
                } else {
                    in = new BufferedReader(new FileReader("input.txt"));
                    out = new PrintWriter("output.txt");
                }
                tok = new StringTokenizer("");
                solve();
                in.close();
                out.close();
                long endTime = System.currentTimeMillis();
                long totalMemory = Runtime.getRuntime().totalMemory();
                long freeMemory = Runtime.getRuntime().freeMemory();
                System.err.println();
                System.err.println("Time = " + (endTime - startTime) + " ms");
                //System.err.println("Memory = " + ((totalMemory - freeMemory) / 1024) + " KB");
            } catch (Throwable e) {
                e.printStackTrace(System.err);
                System.exit(-1);
            }
        };
        new Thread(null, run, "run", 256 * 1024 * 1024).start();
        min(0, 0);
    }

    String readString() {
        while (!tok.hasMoreTokens()) {
            String line;
            try {
                line = in.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            if (line == null) return null;
            tok = new StringTokenizer(line);
        }
        return tok.nextToken();
    }

    int readInt() {
        return Integer.parseInt(readString());
    }

    long readLong() throws IOException {
        return Long.parseLong(readString());
    }

    double readDouble() throws IOException {
        return Double.parseDouble(readString());
    }

    void debug(Object... o) {
        if (!ONLINE_JUDGE) {
            System.err.println(Arrays.deepToString(o));
        }
    }

    long binpow(int a, int n) {
        long r = 1;
        while (n > 0) {
            if ((n & 1) > 0) {
                r *= a;
            }
            a *= a;
            n /= 2;
        }
        return r;
    }

    static long gcd(long x, long y) {
        return y == 0 ? x : gcd(y, x % y);
    }

    private long[] readLongArray(int n) throws IOException {
        long[] a = new long[n];
        for (int i = 0; i < n; i++) {
            a[i] = readLong();
        }
        return a;
    }

    public static void main(String[] args) {
        new Main().run();
    }
}
//  [java]
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner scan = new Scanner(System.in);
		int a = scan.nextInt();
		if (a < 1000) {
			System.out.println("ABC");
		} else {
			System.out.println("ABD");
		}
	}
}
//  [java]
import java.util.Scanner;

public class Main {

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

		int n = scan.nextInt();
		if(n < 1000) {
			System.out.println("ABC");
		} else {
			System.out.println("ABD");
		}
	}
}
//  [cpp]
#include <cstdio>

int main(){
    int N;
    scanf("%d", &N);

    int ans = N / 1000;

    if(ans == 0){
        printf("ABC\n");
    }else{
        printf("ABD\n");
    }

    return 0;
}
//  [cpp]
#include<stdio.h>

int main()
{
	int N;
	scanf("%d",&N);
	
	if(N<=999)
		printf("ABC\n");
	else if(N>999)
		printf("ABD\n");
	
	return 0;
}
//  [cpp]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
 
int main()
{
    int n;
    scanf("%d",&n);
    if(n>=1000) printf("ABD");
    else printf("ABC");
    return 0;
}
//  [cpp]
#include <limits>
#include <iostream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <string>
#include <vector>
#include <bitset>
#include <map>
#include <cstdint>
using namespace std;


int main(){
    int N;
    cin >> N;
    
    cout << (N < 1000 ? "ABC" : "ABD") << '\n';

    return 0;
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;

int main()
{

	int N;
	cin >> N;
	if (N < 1000) {
		cout << "ABC" << endl;
	} else {
		cout << "ABD" << endl;
	}
	return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
#define int long long
int inf = 10e17;
#define mod 1000000007

bool vis[200005];
vector<int> vec[2000005], v1;
int child[2000005];
int parent[2000005];
int div1[100005];
int min_indx[900005];
int count1 = 0;
int height = 0;
int max_indx[200005];
void dfs(int node)
{

    vis[node] = 1;
    // cout << node << "\n";
    min_indx[count1] = node;
    max_indx[node] = min(max_indx[node], count1);
    count1++;

    //  count1++;
    child[node] = height++;
    for (int i = 0; i < vec[node].size(); i++)
    {
        if (!vis[vec[node][i]])
        {
            dfs(vec[node][i]);
            min_indx[count1] = node;
            max_indx[node] = min(max_indx[node], count1);
            count1++;
        }
    }
    height--;
}

int MAXN = 200005;
int LOGMAXN = (int)log2(200005) + 1;
int M[200005][60];
void process2(int A[], int N)
{
    int i, j;

    //initialize M for the intervals with length 1
    for (i = 0; i < N; i++)
        M[i][0] = i;
    //compute values from smaller to bigger intervals
    for (j = 1; 1 << j <= N; j++)
        for (i = 0; i + (1 << j) - 1 < N; i++)
            if (A[M[i][j - 1]] < A[M[i + (1 << (j - 1))][j - 1]])
                M[i][j] = M[i][j - 1];
            else
                M[i][j] = M[i + (1 << (j - 1))][j - 1];
}
//int parent[200005];
vector<int> vec1;
//bool vis[200005];
//int hei[200005];
int lev[200005];
int dis[200005];
bool cmp(pair<int, int> &a,
         pair<int, int> &b)
{
    return a.second < b.second;
}
int32_t main()
{
    // ios_base::sync_with_stdio(false);
    // cin.tie(NULL);
    //  int t;
    int n, m;
    cin >> n;
    if (n > 999)
    {
        cout << "ABD"
             << "\n";
    }
    else
    {
        cout << "ABC"
             << "\n";
    }

    return 0;
}
//  [c]
#include <stdio.h>
#include <string.h>
#define ll long long
#define rep(i,l,r)for(ll i=(l);i<(r);i++)
#define repp(i,l,r,k)for(ll i=(l);i<(r);i+=(k))
#define INF ((1LL<<62)-(1LL<<31))
#define max(p,q)((p)>(q)?(p):(q))
#define min(p,q)((p)<(q)?(p):(q))
#define bit(n,m)((n>>m)&1)
int upll(const void*a, const void*b){return*(ll*)a<*(ll*)b?-1:*(ll*)a>*(ll*)b?1:0;}
int downll(const void*a, const void*b){return*(ll*)a<*(ll*)b?1:*(ll*)a>*(ll*)b?-1:0;}
void sortup(ll*a,int n){qsort(a,n,sizeof(ll),upll);}
void sortdown(ll*a,int n){qsort(a,n,sizeof(ll),downll);}

ll n,ans;
int main(){
	scanf("%lld",&n);
	puts(n>999?"ABD":"ABC");
//	printf("%lld\n",ans);
	return 0;
}
//  [c]
#include<stdio.h>
int main(void){
  int n;
  scanf("%d",&n);
  if(n<=999){
    printf("ABC\n");
  }else{
    printf("ABD\n");
  }
  return 0;
}
//  [c]
#include <stdio.h>
int main() {
    int n;
    scanf("%d", &n);
    printf("%s\n", 1000 > n ? "ABC" : "ABD");
    return 0;
}
//  [c]
#include <stdio.h>

int main (void)
{
    int n;
    scanf("%d",&n);
    if(n<1000)
    {
        puts("ABC");
    }else{
        puts("ABD");
    }
    return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>

int main(){
  int N;
  char S[4]="ABC";
  scanf("%d",&N);
  if(N/1000==1) S[2]++;
  printf("%s\n",S);
  return 0;
}
//  [c]
#include <stdio.h>
int main(){
  int n;
  scanf("%d",&n);
  if(n<1000){ printf("ABC\n"); }
  else		{ printf("ABD\n"); }
  return 0;
}
//  [javascript]
function main(input) {
    var n = input[0]-0;
    console.log(n>=1000?"ABD":"ABC");
    
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"))
//  [javascript]
function Main(input) {
  // 入力値（文字列）をスペースで区切り、配列として格納し各要素の値を数値に変換
  const result = input
  .split(/\s/);
  var test = Number(result[0]);
  if(0 <= test && test < 1000 ){
    console.log('ABC');
  }else {
    console.log('ABD');

  }
};
 
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function Main(input) {
  if(parseInt(input) >= 1000){
     console.log("ABD");
     }else{
     console.log("ABC");
     }
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict'

const main = input => {
	const args = input.split('\n').map(arg => arg.split(' '))
	const N = parseInt(args[0][0], 10)
	if (N > 999) console.log('ABD')
	else console.log('ABC')
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))
//  [javascript]
function Main(s){
	s|=0;
	var ans="ABD";
	if(s<1000){ans="ABC";}
	console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
'use strict'

function Main(input) {
  const N = Number(input);

  if(N <= 999) {
    console.log('ABC');
  } else {
    console.log('ABD');
  }

}

Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [go]
package main

import (
	"fmt"
)

func main() {
	var n int
	fmt.Scan(&n)
	switch {
	case n <= 999:
		fmt.Println("ABC")
	default:
		fmt.Println("ABD")
	}
}
//  [go]
package main

import "fmt"

func main() {
	var n int
	fmt.Scan(&n)
	
	if n <= 999{
		fmt.Println("ABC")
	}else{
		fmt.Println("ABD")
	}
}
//  [go]
package main

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

var sc = bufio.NewScanner(os.Stdin)

func Scanner() string {
	sc.Scan()
	return sc.Text()
}

func intScanner() int {
	n, _ := strconv.Atoi(Scanner())
	return n
}

func floatScanner() float64 {
	n, _ := strconv.ParseFloat(Scanner(), 64)
	return n
}
func stringToInt(s string) int {
	n, _ := strconv.Atoi(s)
	return n
}
func stringSliceScanner(n int) []string {
	a := make([]string, n)
	for i := 0; i < n; i++ {
		a[i] = Scanner()
	}
	return a
}
func intSliceScanner(n int) []int {
	a := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = intScanner()
	}
	return a
}
func larger(a, b int) int {
	if a < b {
		return b
	} else {
		return a
	}
}
func smaller(a, b int) int {
	if a > b {
		return b
	} else {
		return a
	}
}
func max(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x < a[i] {
			x = a[i]
		}
	}
	return x
}
func min(a []int) int {
	x := a[0]
	for i := 0; i < len(a); i++ {
		if x > a[i] {
			x = a[i]
		}
	}
	return x
}
func abs(x int) int {
	if x < 0 {
		x = -x
	}
	return x
}

var mod int = 1000000007

func main() {
	buf := make([]byte, 0)
	sc.Buffer(buf, mod)
	sc.Split(bufio.ScanWords)
	n := intScanner()
	if n <= 999 {
		fmt.Println("ABC")
	} else {
		fmt.Println("ABD")
	}
}
//  [go]
package main

import "fmt"

func main() {
	// Code for A - ABD
	var N int
	fmt.Scanf("%d", &N)

	if N <= 999 {
		fmt.Println("ABC")
	} else {
		fmt.Println("ABD")
	}
}
//  [ruby]
puts gets =~ /1.../ ? "ABD" : "ABC"
//  [ruby]
puts gets.to_i < 1000 ? "ABC" : "ABD"
//  [ruby]
a = gets.to_i
puts a<1000 ? 'ABC' : 'ABD'
//  [ruby]
#!/usr/bin/env ruby

# Generated by AtcoderGreedy on 2018-06-10
# ABC099 A

# my lib

module Enumerable
  # work just like String#split,
  # except this method does not use regex match
  # but check whether yield succeeds or not.
  def split
    current = nil
    ret = []
    each do |elem|
      if yield elem
        if current
          ret << current
          current = nil
        end
      elsif current
        current << elem
      else
        current = [elem]
      end
    end
    ret << current if current
    ret
  end
end

class Array
  # truncate tail, opposite of drop
  def clip(amount = 1)
    if amount < 0
      raise ArgumentError, "amount == #{amount}, cannot be negative!"
    end
    take_amount = size - amount
    take_amount < 0 ? [] : take(take_amount)
  end
end

def n_choose_k(n, k)
  return 0 unless (0..n).cover? k
  result = 1
  1.upto(k) do |d|
    result *= n
    result /= d
    n -= 1
  end
  result
end

# end of lib

# Your code here

N = gets.chomp.to_i

if N >= 1000
  puts 'ABD'
else
  puts 'ABC'
end
//  [ruby]
n = gets.chomp.to_i
if n < 1000
  puts "ABC"
else
  puts "ABD"
end
//  [ruby]
n = gets.to_i
if 1 <= n && n <= 999
  puts "ABC"
else
  puts "ABD"
end
//  [rust]
#![allow(unused_imports)]
#![allow(dead_code)]
use proconio::input;
use proconio::fastout;
use proconio::marker::{Chars};

#[fastout]
fn main() {
    input! {
        a:i32,
    }
    if a<=999{
        println!("{}","ABC");
    }else{
        println!("{}","ABD");
    }
}
//  [rust]
use std::io;
use std::str::FromStr;

fn input<T:FromStr>() -> T {
    let mut line: String = String::new();
    io::stdin().read_line(&mut line);
    line.trim().parse().ok().unwrap()
}

fn main() {
    let n: u64 = input();
    if n <= 999 {
        println!("ABC");
    } else {
        println!("ABD")
    }
}
//  [rust]
use std::io::*;
use std::str::FromStr;

pub fn read<T: FromStr>() -> T {
    let stdin = stdin();
    let stdin = stdin.lock();
    let token: String = stdin
        .bytes()
        .map(|c| c.expect("failed to read char") as char)
        .skip_while(|c| c.is_whitespace())
        .take_while(|c| !c.is_whitespace())
        .collect();
    token.parse().ok().expect("failed to parse token")
}

fn main() {
    let n: usize = read();

    if n >= 1000 {
        println!("ABD")
    } else {
        println!("ABC")
    }
}
//  [rust]
#[allow(unused_imports)] use proconio::{input, marker::{Bytes, Chars, Usize1, Isize1}};
#[allow(unused_imports)] use std::cmp::{min, max};
#[allow(unused_imports)] use superslice::Ext as _;

#[proconio::fastout]
fn main() {
	input! {
		n: usize,
	}

	if n < 1000 {
		println!("ABC");
	}
	else {
		println!("ABD");
	}
}
//  [rust]
use proconio::{input, fastout};
use proconio::marker::{Chars};
use proconio::marker::Usize1;
use std::cmp::*;

macro_rules! debug {
      ($($a:expr),*) => {
          eprintln!(concat!($(stringify!($a), " = {:?}, "),*), $($a),*);
      }
  }

#[fastout]
fn main() {
    input!{
        n: usize,
    }

    match n {
        1...999 => println!("ABC"),
        1000...1998 => println!("ABD"),
        _ => return,
    }

}
//  [swift]
print(Int(readLine()!)!>999 ?"ABD":"ABC")
//  [swift]
let n = Int(readLine() ?? "0") ?? 0
if n < 1000 {
  print("ABC")
} else {
  print("ABD")
}
//  [swift]
if let n = Int16(readLine()!) {
    if n > 999 {
        print("ABD")
    } else {
        print("ABC")
    }
}
//  [swift]
let number = Int(readLine()!)!
if number < 1000 {
  print("ABC")
} else {
  print("ABD")
}
//  [swift]
/// Swift5 -> Swift2.2

extension String {
    // split(separator:maxSplits:omittingEmptySubsequences:)
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map(String.init)
    }
}
extension Array {
    // init(repeating:count:)
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
    // lastIndex(where:)
    func lastIndex(where predicate: (Element) -> Bool) -> Int? {
      	for i in stride(from: count - 1, through: 0, by: -1) {
          	if predicate(self[i]) {
              	return i
            }
        }
      	return nil
    }
}
extension Array where Element: Comparable {
    // sorted()
    func sorted() -> [Element] {
        return self.sort( { $0 < $1 } )
    }
    // max()
    func max() -> Element? {
        guard self.count > 0 else { return nil }
        return self.reduce(self.first!) { return Swift.max($0, $1) }
    }
}
extension String {
    // Sequence#enumerated()
  	// public func enumerate<Seq : SequenceType>(base: Seq) -> EnumerateSequence<Seq>
    func enumerated() -> EnumerateSequence<[Character]> {
        return Array(self.characters).enumerate()
    }
}
// stride(from:through:by:)
func stride(from start: Int, through end: Int, by stride: Int) -> StrideThrough<Int> {
    return start.stride(through: end, by: stride)
}
// stride(from:to:by)
func stride(from start: Int, to end: Int, by stride: Int) -> StrideTo<Int> {
    return start.stride(to: end, by: stride)
}

/// end


let N = Int(readLine()!)!

print(N >= 1000 ? "ABD" : "ABC")
//  [typescript]
const Main = (input: string): void => {
	const num = parseInt(input)
	if (num < 1000) {
		console.log("ABC")
	} else {
		console.log("ABD")
	}
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"))
//  [typescript]
const stdin = require('fs').readFileSync('/dev/stdin', 'utf8')

const i = stdin.split('\n')[0]

const n = Number(i)

let res = ''
if(n<1000){
  res = 'ABC'
} else {
  res = 'ABD'
}

console.log(res)
//  [typescript]
const input=require('fs').readFileSync('/dev/stdin', 'utf8').split(/[\s]/);const nin=()=>{const r = input[0];input.shift();return Number(r)};const nrin=(n)=>{const a:number[]=[];rep(n,()=>a.push(nin()));return a};const sin=()=>{const r = input[0];input.shift();return String(r)};const out=(...a)=>{console.log(...a)};const floor=(a)=>{return Math.floor(a)};const abs=(a)=>{return Math.abs(a)};const min=(...a)=>{return Math.min(...a)};const max=(...a)=>{return Math.max(...a)};const rep=(n, callback)=>{for(let i = 0;i < n; i++){callback()}};const strrep=(s, i, v)=>{return s.slice(0, i)+v+s.slice(i+1);};const permutation=({result=[],pre=[],post,n=post.length})=>{if(n>0){post.forEach((_,i)=>{const rest=[...post];const elem=rest.splice(i, 1);permutation({result, pre: [...pre,...elem],post:rest,n:n-1})})}else{result.push(pre)}return result};const sw=(s,a:any[],op:'=='|'>='|'>'|'<='|'<'='==')=>{for(let i=0;i<a.length;i+=2){if(op==='=='){if(s==a[i])return a[i+1]}else if(op==='>='){if(s>=a[i])return a[i+1]}else if(op==='<='){if(s<=a[i])return a[i+1]}else if(op==='>'){if(s>a[i])return a[i+1]}else if(op==='<'){if(s<a[i])return a[i+1]}}return a[a.length-1];};const or=(a,...b)=>{for(let i=0;i<b.length;i++)if(a==b[i])return true;return false};const maxindex=(...a)=>{return a.indexOf(Math.max.apply(null,a))};const asc=(ar:number[])=>{return ar.sort((a,b)=>{return a-b})};const desc=(ar:number[])=>{return ar.sort((a,b)=>{return b-a})};const ceil=a=>{return Math.ceil(a)};const srin=s=>{const a:string[]=[];rep(s,()=>a.push(sin()));return a};let ssinteger=-1;const ssin=()=>{ssinteger++;return input[0][ssinteger]};
const main = ()=>{
  // let n=nin()
  out(nin()>=1000?'ABD':'ABC')
  
}
main();
//  [typescript]
import { readFileSync } from "fs";

const read = () =>
  readFileSync(0, "utf8")
    .split("\n")
    .map((line) => line.split(" "));

const main = (input: string[][]) => {
  const N = Number(input[0][0]);

  return N >= 1000 ? "ABD" : "ABC";
};

console.log(main(read()));
//  [typescript]
import * as fs from 'fs';

const input = (fs.readFileSync('/dev/stdin', 'utf8') as string).split('\n');

const N = +input[0];

if (N < 1000) {
  console.log('ABC');
} else {
  console.log('ABD');
}
//  [typescript]
const main = (input) => {
  input = input.trim();
  input = input.split(' ');
  const n = parseInt(input[0], 10);
  
  if (n<1000) {
    console.log("ABC");
  }else{
    console.log("ABD");
  }
 
  
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));
//  [python]
x_str = input()
x = int(x_str)
digits = [int(a) for a in x_str]
fx = sum(digits)
if x % fx == 0:
  print("Yes")
else:
  print("No")
//  [python]
n=input()
l=list(n);l=[int(i) for i in l]
n=int(n)
if n%sum(l)==0:print('Yes')
else:print('No')
//  [python]
n = input()
total = 0
for i in n:
    total += int(i)
if int(n) % total == 0:
    print('Yes')
else:
    print('No')
//  [python]
def f(x):
	q = 0
	c = x
	while(x):
	  q += x % 10
	  x /=10
	return c and c % q == 0
print 'Yes' if f(int(raw_input())) else 'No'
//  [python]
n = int(input())
s = sum(list(map(int,str(n))))
print('Yes' if n%s==0 else 'No')
//  [python]
# region header
import sys
import math
from bisect import bisect_left, bisect_right, insort_left, insort_right
from collections import defaultdict, deque, Counter
from copy import deepcopy
from fractions import gcd
from functools import lru_cache, reduce
from heapq import heappop, heappush
from itertools import accumulate, groupby, product, permutations, combinations, combinations_with_replacement
from math import ceil, floor, factorial, log, sqrt, sin, cos
from operator import itemgetter
from string import ascii_lowercase, ascii_uppercase, digits
sys.setrecursionlimit(10**7)
rs = lambda: sys.stdin.readline().rstrip()
ri = lambda: int(rs())
rf = lambda: float(rs())
rs_ = lambda: [_ for _ in rs().split()]
ri_ = lambda: [int(_) for _ in rs().split()]
rf_ = lambda: [float(_) for _ in rs().split()]
INF = float('inf')
MOD = 10 ** 9 + 7
PI = math.pi
# endregion
N = ri()
f = sum([int(i) for i in str(N)])
print('Yes' if N % f == 0 else 'No')