(function(input) {
    var p = input.split('\n');
    var n = p.shift();
    var a = p.slice(0, n);
    var count = 0;
    var g = [];
    for (var i = 0;; i++) {
        var m = Math.pow(2, i);
        if (m > a.length) {
            break;
        }
        g.unshift(m);
    }
    sortShell(a, g);
    console.log(g.length);
    console.log(g.join(' '));
    console.log(count);
    console.log(a.join('\n'));

    function sortShell(a, g) {
        for (var i = 0; i < g.length; i++) {
            sortInsertion(a, g[i]);
        }

        function sortInsertion(a, g) {
            //console.log(a.join(' '));
            for (var i = g; i < a.length; i += g) {
                var v = a[i];
                var j = i - g;
                while (j >= 0 && a[j] > v) {
                    a[j + g] = a[j];
                    j -= g;
                    count++;
                }
                a[j + g] = v;
                //console.log(a.join(' '));
            }
        }
    }

})(require('fs').readFileSync('/dev/stdin', 'utf8'));

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

MathJax.Hub.Config({ tex2jax: { inlineMath: [["$","$"], ["\\(","\\)"]], processEscapes: true }});

Shell Sort

Shell Sort is a generalization of Insertion Sort to arrange a list of $n$ elements $A$.

1 insertionSort(A, n, g)
2 for i = g to n-1
3 v = A[i]
4 j = i - g
5 while j >= 0 && A[j] > v
6 A[j+g] = A[j]
7 j = j - g
8 cnt++
9 A[j+g] = v
10
11 shellSort(A, n)
12 cnt = 0
13 m = ?
14 G[] = {?, ?,..., ?}
15 for i = 0 to m-1
16 insertionSort(A, n, G[i])

A function shellSort(A, n) performs a function insertionSort(A, n, g), which considers every $g$-th elements. Beginning with large values of $g$, it repeats the insertion sort with smaller $g$.

Your task is to complete the above program by filling ?. Write a program which reads an integer $n$ and a sequence $A$, and prints $m$, $G_i (i = 0, 1, ..., m − 1)$ in the pseudo code and the sequence $A$ in ascending order. The output of your program must meet the following requirements:

$1 \leq m \leq 100$

$0 \leq G_i \leq n$

cnt does not exceed $\lceil n^{1.5}\rceil$

Input

In the first line, an integer $n$ is given. In the following $n$ lines, $A_i (i=0,1,...,n-1)$ are given for each line.

Output

In the first line, print an integer $m$. In the second line, print $m$ integers $G_i (i=0,1,...,m-1)$ separated by single space character in a line.

In the third line, print cnt in a line. In the following $n$ lines, print $A_i (i=0,1,...,n-1)$ respectively.

This problem has multiple solutions and the judge will be performed by a special validator.

Constraints

$1 \leq n \leq 1,000,000$

$0 \leq A_i \leq 10^9$

Sample Input 1

5
5
1
4
3
2

Sample Output 1

2
4 1
3
1
2
3
4
5

Sample Input 2

3
3
2
1

Sample Output 2

1
1
3
1
2
3

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


(function(input) {
    var p = input.split('\n').map(Number);
    var n = p.shift();
    var a = p.slice(0, n);
    var count = 0;
    var g = [];
    for (var i = 0;; i++) {
        var m = Math.pow(4, i);
        if (m > a.length) {
            break;
        }
        g.unshift(m);
    }
    sortShell(a, g);
    console.log(g.length);
    console.log(g.join(' '));
    console.log(count);
    console.log(a.join('\n'));

    function sortShell(a, g) {
        for (var i = 0; i < g.length; i++) {
            sortInsertion(a, g[i]);
        }

        function sortInsertion(a, g) {
            //console.log(a.join(' '));
            for (var i = g; i < a.length; i++) {
                var v = a[i];
                var j = i - g;
                while (j >= 0 && a[j] > v) {
                    a[j + g] = a[j];
                    j -= g;
                    count++;
                }
                a[j + g] = v;
                //console.log(a.join(' '));
            }
        }
    }

})(require('fs').readFileSync('/dev/stdin', 'utf8'));


var input = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n').map(Number);
var n = input.shift();
var m = 0;
var g = [1];
var count = 0;

function insertionSort(array, n, g) {
  for (var i = g; i < array.length; i++) {
    var v = array[i];
    var j = i - g;
    while (j >= 0 && array[j] > v) {
      var tmp = array[j + g];
      array[j + g] = array[j];
      array[j] = tmp;
      j -= g;
      count++;
    }
  }
}

function shellSort(array, n) {
  m = Math.floor(array.length / 3);
  for (var i = 1; i < m; i++) {
    g[i] = g[i - 1] * 3 + 1;
  }
  g = g.filter(function(j) {
    return (j < n);
  });
  m = g.length;
  g.reverse();

  for (var i = 0; i < m; i++) {
    insertionSort(array, n, g[i]);
  }

  return array;
}

var sorted = shellSort(input, n);
console.log(m);
console.log(g.join(' '));
console.log(count);
console.log(sorted.join('\n'));


var cnt;

function insertionSort(A, n, g) {
	for (var i = g; i < n; i++) {
		var v = A[i];
		var j = i - g;
		while (j >=0 && A[j] > v) {
			A[j + g] = A[j];
			j = j - g;
			cnt ++;
		}
		A[j + g] = v;
	}
}

function shellSort(A, n) {
	cnt = 0;

	var G = [];
	for (var i = 0; i * 3 + 1 <= n; i++) {
		G.push(i * 3 + 1);
	}
	G.reverse();
	var m = G.length;

	for (var i = 0; i < m; i++) {
		insertionSort(A, n, G[i]);
	}

	console.log(m);
	console.log(G.join(' '));
	console.log(cnt);
	for (var i = 0; i < n; i++) {
		console.log(A[i]);
	}
}

var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');
var n = lines.shift();

shellSort(lines, n);


'use strict';

waterfall([
  function(next) {
    lineReader(1, next);
  }, function(line, next) {
    lineReader(parseInt(line[0]), next);
  }, function(lines, next) {
    lines.reduce(function(hash, line) {
      var command = line.split(' ')[0];
      var key = line.split(' ')[1];
      if (command === 'insert') {
        hash[key] = true;
        return hash;
      }
      if (hash[key]) {
        console.log('yes');
      } else {
        console.log('no');
      }
      return hash;
    }, {})
    next(null);
  }], function(result) {
    process.exit(0);
  });

function strMap(str, map) {
  var newStr = '';
  for (var i = 0; i < str.length; i++) {
    newStr += map(str.charAt(i), i);
  }
  return newStr;
}

function lineReader(limit, cb) {
  var reader = require('readline').createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  var lines = [];
  var counter = 0;
  reader.on('line', function(line) {
    lines.push(line);
    ++counter;
    if (counter === limit) {
      reader.close();
      return cb(lines);
    }
  });
  reader.on('close', function() {});
  reader.on('error', function(err) {
    cb(err);
  });
}

function waterfall(tasks, cb) {
  var taskIndex = 0;
  function nextTask(args) {
    if (taskIndex === tasks.length)
      return cb.apply(null, args);

    var taskCallback = function() {
      var _arguments = arguments;
      nextTask(Object.keys(_arguments).reduce(function(memo, key) {
        memo.push(_arguments[key]);
        return memo;
      }, []));
    };
    args.push(taskCallback);
    var task = tasks[taskIndex++];
    task.apply(null, args);
  }
  nextTask([]);
}

Search III

Your task is to write a program of a simple dictionary which implements the following instructions:

insert str: insert a string str in to the dictionary

find str: if the distionary contains str, then print 'yes', otherwise print 'no'

Input

In the first line n, the number of instructions is given. In the following n lines, n instructions are given in the above mentioned format.

Output

Print yes or no for each find instruction in a line.

Constraints

A string consists of 'A', 'C', 'G', or 'T'

1 ≤ length of a string ≤ 12

n ≤ 1000000

Sample Input 1

5
insert A
insert T
insert C
find G
find A

Sample Output 1

no
yes

Sample Input 2

13
insert AAA
insert AAC
insert AGA
insert AGG
insert TTT
find AAA
find CCC
find CCC
insert CCC
find CCC
insert T
find TTT
find T

Sample Output 2

yes
no
no
yes
yes
yes

Notes

Template in C


'use strict';

var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = (input.trim()).split('\n');
lines.shift();
var hash = {};

lines.forEach(function(line) {
  var cmd = line.split(' ')[0];
  var key = line.split(' ')[1];
  if (cmd === 'insert') {
    hash[key] = true;
    return;
  }
  if (hash[key]) {
    console.log('yes');
  } else {
    console.log('no');
  }
});


process.stdin.resume();
process.stdin.setEncoding('utf8');

process.stdin.on('data', function (chunk) {
    var xs = chunk.toString().trim().split('\n').slice(1).map(function(x){ return x.split(' '); });
    var ys = {};
    xs.forEach(function(x){
        if(x[0] === 'insert'){
            ys[x[1]] = true;
        }else if(x[0] === 'find'){
            console.log(ys.hasOwnProperty(x[1]) ? 'yes' : 'no');
        }
    });
});


class ACGTHashList {
  static get MAP() {
    return {
      'A': 1,
      'C': 2,
      'G': 3,
      'T': 4,
    }
  }

  constructor(M) {
    this.M = M;
    this.H = [];
    for (let i = 0; i < M; i++) this.H[i] = '';
  }

 static _getKey(str) {
   let sum = 0;
   let p = 1;
   for (let i = 0, p = 1; i < str.length; i++, p *= 5) sum += p * ACGTHashList.MAP[str[i]];
   return sum;
 }

 _h1(key) { return key % this.M;}

 _h2(key) { return 1 + key % (this.M - 1);}

 find(str) {
   let key = ACGTHashList._getKey(str);
   let h;
   const h1 = this._h1(key), h2 = this._h2(key);
   for (let i = 0;; i++) {
     h = (h1 + i * h2) % this.M;
     if (this.H[h] === str) return 1;
     else if (this.H[h] === '') return 0;
   }
   return 0;
 }

 insert(str) {
   let key = ACGTHashList._getKey(str);
   let h;
   const h1 = this._h1(key), h2 = this._h2(key);
   for (let i = 0;; i++) {
     h = (h1 + i * h2) % this.M;
     if (this.H[h] === str) return 1;
     else if (this.H[h] === '') {
       this.H[h] = str;
       return 0;
     }
   }
   return 0;
 }

}

(function main(){
  const lines = require('fs').readFileSync('/dev/stdin', 'utf8');
  var Arr=(lines.trim()).split("\n").slice(1);
  console.log(Arr);
  const commands = Arr.map(l => l.split(' '));

  let hl = new ACGTHashList(1046527);
  commands.forEach(cmd => {
    if (cmd[0][0] === 'i') {
      hl.insert(cmd[1]);
    } else {
      console.log(hl.find(cmd[1]) ? 'yes' : 'no');
    }
  });
})();


var input = require('fs').readFileSync('/dev/stdin', 'utf8');
var lines = input.split('\n');

lines.shift();

var dic = {};
lines.forEach(function (line) {
	var command = line.split(' ');
	if (command[0] == 'insert')
		dic[command[1]] = true;
	else {
		if (dic[command[1]]) {
			console.log('yes');
		} else {
			console.log('no');
		}
	}
});


process.stdin.resume()
process.stdin.setEncoding("utf8")

const reader = require("readline").createInterface({
  input: process.stdin,
  output: process.stdout,
})

const lines = []

reader.on("line", (line) => {
  lines.push(line)
})

reader.on("close", () => {
  const n = lines[0] - 0
  const hm = new HM()
  for (let i = 1; i <= n; i++) {
    const [method, arg] = lines[i].split(" ")
    if (method === "insert") {
      hm.insert(arg)
    } else if (method === "find") {
      console.log(hm.find(arg) ? "yes" : "no")
    }
  }
})

const m = 1000003

const strToNumber = (str) => {
  let numWeight = 1
  let numWeightPerDigit = 4
  let ret = 0
  str
    .split("")
    .reverse()
    .forEach((c) => {
      let num = 0
      switch (c) {
        case "A":
          num = 1
          break
        case "C":
          num = 2
          break
        case "G":
          num = 3
          break
        case "T":
          num = 4
          break
      }
      ret += num * numWeight
      numWeight *= numWeightPerDigit
    }, 0)

  return ret
}

function h1(key) {
  return key % m
}

function h2(key) {
  return 1 + (key % (m - 1))
}

function h(key, i) {
  return (h1(key) + i * h2(key)) % m
}

class HM {
  constructor() {
    this.T = Array(m)
  }

  insert(str) {
    let i = 0,
      j
    const key = strToNumber(str)
    const T = this.T
    while (true) {
      j = h(key, i)
      if (T[j] == null) {
        T[j] = key
        return j
      } else {
        i++
      }
    }
  }

  find(str) {
    let i = 0,
      j
    const key = strToNumber(str)
    const T = this.T
    while (true) {
      j = h(key, i)
      if (T[j] === key) {
        return true
      } else if (T[j] == null || i >= m) {
        return false
      } else {
        i++
      }
    }
  }
}


class dictionary{
    constructor(m){
        this.S = new Array(m);
        this.m = m;
    }

    h1(key){
        return key % this.m;
    }
    h2(key){
        return 1 + key % (this.m-1);
    }
    h(key,i){
        return (this.h1(key)+i*this.h2(key)) % this.m;
    }
    insert(key){
        let i = 0;
        while(true){
            let j = this.h(key,i);
            if(typeof this.S[j]==="undefined"){
                this.S[j] = key;
                return j;
            }else{
                i++;
            }
        }
    }
    search(key){
        let i = 0;
        while(true){
            let j = this.h(key,i);
            if(this.S[j]===key){
                return j;
            }else if(i>=this.m || typeof this.S[j]==="undefined"){
                return false;
            }else{
                i++;
            }
        }
    }
}

function main(input){
    let lines = input.trim().split("\n");
    let length = parseInt(lines.shift());
    let dict = new dictionary(length);

    for(let i =0;i<length;i++){
        let args = lines[i].trim().split(" ");
        args[1] = args[1].replace(/A/g,"1");
        args[1] = args[1].replace(/C/g,"2");
        args[1] = args[1].replace(/G/g,"3");
        args[1] = args[1].replace(/T/g,"4");

        if(args[0]==="insert"){
            dict.insert(parseInt(args[1]));
        }else if(args[0]==="find"){
            let res = dict.search(parseInt(args[1]));
            if(typeof res==="number") console.log("yes");
            else console.log("no");
        }

    }

}

main(require("fs").readFileSync("/dev/stdin","utf-8"));


(async () => {
    let input = '';
    for await (const chunk of process.stdin) input += chunk;
    let values = input.split(/\s/).map(v => +v);

    const length = values.shift();
    values = values.slice(0, length);

    let sum = 0;
    let tmp = 0;
    for (let i = length - 2; i >= 0; i--) {
        tmp += values[i + 1];
        sum = (sum + values[i] * tmp) % (1e9 + 7);
    }

    console.log(sum % (1e9 + 7));

})();

Score : 300 points

Problem Statement

Given are N integers A_1,\ldots,A_N.

Find the sum of A_i \times A_j over all pairs (i,j) such that 1\leq i < j \leq N, modulo (10^9+7).

Constraints

2 \leq N \leq 2\times 10^5

0 \leq A_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

Print \sum_{i=1}^{N-1}\sum_{j=i+1}^{N} A_i A_j, modulo (10^9+7).

Sample Input 1

3
1 2 3

Sample Output 1

11

We have 1 \times 2 + 1 \times 3 + 2 \times 3 = 11.

Sample Input 2

4
141421356 17320508 22360679 244949

Sample Output 2

437235829


function Main(input) {
  input = input.split("\n");
  const N = parseInt(input[0], 10);
  const A = input[1].split(" ").map(n => parseInt(n, 10));

  var count = 0;
  var sum = 0;

  A.forEach(function(a) {
    sum += a;
  });

  for(var i = 0; i < (N-1); i++){
    sum-=A[i]
    count+=A[i]*sum
    count = count%1000000007
  }

  console.log(count);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(arg) {

    let n = Number(arg.split("\n")[0])
    let a = arg.split("\n")[1].split(" ").map(Number)

    let mod = 10**9+7
    let sum = new Array(n+1)
    sum[0] = a[0]
    for(let i=0; i<n; i++) {
        sum[i+1] = (sum[i]+a[i]) % mod
    }
    //console.log(sum)

    let ans=0
    for(let i=0; i<n; i++) {
        //console.log(`${a[i]} * ${sum[i]} = ${a[i]*sum[i]}`)
        //ans += (a[i]*sum[i])
        ans += ((sum[n]-sum[i+1])%mod) * a[i]
        ans %= mod
    }
    console.log(ans)

}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


((input) => {
  const arr = input.trim().split('\n')[1].split(' ');
  const l = arr.length;
  const n = 1000000007;
  let sum = 0;

  for (let i = 0; i < l - 1; i++) {
    for (let j = i + 1; j < l; j++) {
      sum += arr[i] % n * arr[j] % n;
    }
  }

  console.log(sum % n);
})(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  const lines = input.split('\n');
  const N = lines[0];
  const A = lines[1].split(' ').map(i => parseInt(i));
  const D = Math.pow(10, 9) + 7;
  const notes = [];
  let sum = 0;
  A.reverse().map(a => {
    sum += a;
    sum = sum % D;
    notes.push(sum);
  });
  notes.reverse();
  A.reverse();
  console.log(A);
  console.log(notes);
  sum = 0;
  A.forEach((a, i) => {
    if (i !== N - 1) {
      console.log(a, notes[i+1]);
      sum += (a * notes[i+1]) % D;
    }
  });
  console.log(sum % D);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
  input = input.split("\n");
  const N = input[0];
  const A = input[1].split(" ");

  var count = 0;

  for(var i = 0; i < (N-1); i++){
    for(var j = i+1; j < N; j++){
      count += (A[i]%1000000007)*(A[j]%1000000007)
    }
  }

  console.log(count%1000000007);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    tmp = input.split("\n");
    n = parseInt(tmp[0], 10);
    a = tmp[1].split(" ").map(Number);
    MOD = 1000000007;
	result = 0;

    for (let i = 0; i < n; i++) {

        for (let j = 1; j < n; j++) {
			num1 = a[i] % MOD;
            num2 = a[j] % MOD;

            if (i < j) {
           		result += (num1  * num2) % MOD;
            	result = result % MOD
            }
        }
    }

    console.log(result);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


const main = (input) => {
  input = input.trim().split('\n')
  const mod = 10n**9n + 7n
  const arr = input[1].split(' ').map(BigInt).sort((a, b) => b - a)

  let sum = arr[0] + arr[1]
  let ans = arr[0] * arr[1] % mod

  for (let i=2; i<arr.length; i++) {
    ans += sum * arr[i] % mod
    sum += arr[i]
  }

  return console.log(`${ans % mod}`)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


const main = (input) => {
  input = input.trim().split('\n')
  const mod = BigInt(10**9 + 7)
  const arr = input[1].split(' ').map(BigInt).sort((a, b) => a - b)

  let ans = 0n

  for (let i=0; i<arr.length-1; i++) {
    for (let e=i+1; e<arr.length; e++) {
      ans += arr[i] * arr[e] % mod
    }
  }

  return console.log(`${ans % mod}`)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


const SieveOfEratosthenes = (n) => {
    let flg = (new Array(n)).fill(0)/* set flg[i] to true when it is seived */
    let primes = []/* list of prime numbers */
    for(let i=2; i*i<=n; i++) {
        if(!flg[i]) {
            primes.push(i)
            for(let j=i; j*j<=n; j+=i) {
                flg[j] = 1
            }
        }
    }
    return primes
}

const factorizationBySoE = (n, primes) => {
    //const primes = SieveOfEratosthenes(n)
    let factors = {}
    primes.some(p => {
        if(n < p) return true
        while(n%p===0) {
            if(!factors[p])factors[p]=1
            else factors[p]++
            n/=p
        }
    })
    if(n>1)factors[n]=1
    return factors
}

const getGCD = (a,b) => {
    if(b===0)return a
    else if(a===0)return b
    return getGCD(b, a%b)
}

const main = (arg) => {
    const N = Number(arg.split("\n")[0])
    const a = arg.split("\n")[1].split(" ").map(Number)

    const MAX_A = 10**6+100
    const A = Math.max(...a)

    //  check if p is in {a} (paircoprime)
    //const primes = SieveOfEratosthenes(A)
    let set = [...new Array(MAX_A+100)].fill(0)
    isPairCoprime = true
  /*
    for(let i=0; i<N; i++) {
        const factors = Object.keys(factorizationBySoE(a[i], primes))
        for(let j=0; j<factors.length; j++ ) {
            // console.log(`i=${i}, j=${j}, ${factors[j]}`)
            // console.log(factors)
            if(set[factors[j]] === 1) {
                isPairCoprime = false
            }
            set[factors[j]] = 1
        }
    }
*/
    for(let i=0; i<MAX_A; i++) {
        set[a[i]] = 1
    }
    for(let i=2; i<MAX_A; i++) {
         let cnt=0
         for(let j=i; j<MAX_A; j+=i) {
             cnt+=set[j]
         }
        if(cnt>1) {
             isPairCoprime = false
         }
     }

    if(isPairCoprime) {
        console.log("pairwise coprime")
        return
    }

    // setcoprime
    // let gcd = getGCD(a[0], a[1])
    let gcd = 0
    for(let i=0; i<a.length; i++) {
        gcd = getGCD(gcd, a[i])
        // console.log(gcd)
    }

    if(gcd===1) {
        console.log("setwise coprime")
        return
    }

    console.log("not coprime")
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));

Score : 500 points

Problem Statement

We have N integers. The i-th number is A_i.

\{A_i\} is said to be pairwise coprime when GCD(A_i,A_j)=1 holds for every pair (i, j) such that 1\leq i < j \leq N.

\{A_i\} is said to be setwise coprime when \{A_i\} is not pairwise coprime but GCD(A_1,\ldots,A_N)=1.

Determine if \{A_i\} is pairwise coprime, setwise coprime, or neither.

Here, GCD(\ldots) denotes greatest common divisor.

Constraints

2 \leq N \leq 10^6

1 \leq A_i\leq 10^6

Input

Input is given from Standard Input in the following format:

N
A_1 \ldots A_N

Output

If \{A_i\} is pairwise coprime, print pairwise coprime; if \{A_i\} is setwise coprime, print setwise coprime; if neither, print not coprime.

Sample Input 1

3
3 4 5

Sample Output 1

pairwise coprime

GCD(3,4)=GCD(3,5)=GCD(4,5)=1, so they are pairwise coprime.

Sample Input 2

3
6 10 15

Sample Output 2

setwise coprime

Since GCD(6,10)=2, they are not pairwise coprime. However, since GCD(6,10,15)=1, they are setwise coprime.

Sample Input 3

3
6 10 16

Sample Output 3

not coprime

GCD(6,10,16)=2, so they are neither pairwise coprime nor setwise coprime.


const SieveOfEratosthenes = (n) => {
    let flg = (new Array(n)).fill(0)/* set flg[i] to true when it is seived */
    let primes = []/* list of prime numbers */
    for(let i=2; i*i<=n; i++) {
        if(!flg[i]) {
            primes.push(i)
            for(let j=i; j*j<=n; j+=i) {
                flg[j] = 1
            }
        }
    }
    return primes
}

const factorizationBySoE = (n, primes) => {
    //const primes = SieveOfEratosthenes(n)
    let factors = {}
    primes.some(p => {
        if(n < p) return true
        while(n%p===0) {
            if(!factors[p])factors[p]=1
            else factors[p]++
            n/=p
        }
    })
    if(n>1)factors[n]=1
    return factors
}

const getGCD = (a,b) => {
    if(b===0)return a
    else if(a===0)return b
    return getGCD(b, a%b)
}

const main = (arg) => {
    const N = Number(arg.split("\n")[0])
    const a = arg.split("\n")[1].split(" ").map(Number)
    const MAX_A = 10**6
    const A = Math.max(...a)

    //  check if p is in {a} (paircoprime)
    const primes = SieveOfEratosthenes(A)
    let set = [...new Array(MAX_A)].fill(0)
    isPairCoprime = true
    for(let i=0; i<N; i++) {
        const factors = Object.keys(factorizationBySoE(a[i], primes))
        for(let j=0; j<factors.length; j++ ) {
            // console.log(`i=${i}, j=${j}, ${factors[j]}`)
            // console.log(factors)
            if(set[factors[j]] === 1) {
                isPairCoprime = false
            }
            set[factors[j]] = 1
        }
    }

    // for(let i=0; i<MAX_A; i++) {
    //     set[a[i]] = 1
    // }
    // for(let i=2; i<MAX_A; i++) {
    //     let cnt=0
    //     for(let j=i; j<MAX_A; j+=i) {
    //         cnt+=set[j]
    //     }
    //     if(cnt>1) {
    //         isPairCoprime = false
    //     }
    // }

    if(isPairCoprime) {
        console.log("pairwise coprime")
        return
    }

    // setcoprime
    // let gcd = getGCD(a[0], a[1])
    let gcd = 0
    for(let i=0; i<a.length; i++) {
        // gcd = getGCD(gcd, a[i])
        // console.log(gcd)
    }

    if(gcd===1) {
        console.log("setwise coprime")
        return
    }

    console.log("not coprime")
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


const SieveOfEratosthenes = (n) => {
    let flg = (new Array(n)).fill(0)/* set flg[i] to true when it is seived */
    let primes = []/* list of prime numbers */
    for(let i=2; i*i<=n; i++) {
        if(!flg[i]) {
            primes.push(i)
            for(let j=i; j*j<=n; j+=i) {
                flg[j] = 1
            }
        }
    }
    return primes
}

const factorizationBySoE = (n, primes) => {
    //const primes = SieveOfEratosthenes(n)
    let factors = {}
    primes.some(p => {
        if(n < p) return true
        while(n%p===0) {
            if(!factors[p])factors[p]=1
            else factors[p]++
            n/=p
        }
    })
    if(n>1)factors[n]=1
    return factors
}

const getGCD = (a,b) => {
    if(b===0)return a
    else if(a===0)return b
    return getGCD(b, a%b)
}

const main = (arg) => {
    const N = Number(arg.split("\n")[0])
    const a = arg.split("\n")[1].split(" ").map(Number)
    const MAX_A = 10**6 + 5

    //  check if p is in {a} (paircoprime)
    // const primes = SieveOfEratosthenes(MAX_A)
    let set = [...new Array(MAX_A)].fill(0)
    isPairCoprime = true
    // for(let i=0; i<N; i++) {
    //     const factors = Object.keys(factorizationBySoE(a[i], primes))
    //     for(let j=0; j<factors.length; j++ ) {
    //         // console.log(`i=${i}, j=${j}, ${factors[j]}`)
    //         // console.log(factors)
    //         if(set[factors[j]] === 1) {
    //             isPairCoprime = false
    //         }
    //         set[factors[j]] = 1
    //     }
    // }
    for(let i=0; i<MAX_A; i++) {
        set[a[i]] = 1
    }
    // console.log(a)
    // console.log(set)

    for(let i=2; i<MAX_A; i++) {
        let cnt=0
        for(let j=i; j<MAX_A; j+=i) {
            cnt+=set[j]
        }
        if(cnt>1) {
            isPairCoprime = false
        }
    }

    if(isPairCoprime) {
        console.log("pairwise coprime")
        return
    }
  return

    // setcoprime
    // let gcd = getGCD(a[0], a[1])
    let gcd = 0
    for(let i=0; i<a.length; i++) {
        //gcd = getGCD(gcd, a[i])
        // console.log(gcd)
    }

    if(gcd===1) {
        console.log("setwise coprime")
        return
    }

    console.log("not coprime")
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


(async () => {
    let input = '';
    for await (const chunk of process.stdin) input += chunk;
    let values = input.split(/\s/).map(v => +v);

    const n = values.shift();
    values = values.slice(0, n);
    const max = values.reduce((a, b) => Math.max(a, b), 0);

    let prims = new Array(max - 2);
    for(let i = 2; i <= max; i++){
        if(!prims[i - 2]){
            prims[i - 2] = i;
            for(let j = i * 2; j <= max; j += i){
                if(!prims[j - 2]){
                    prims[j - 2] = i;
                }
            }
        }
    }

    const gcd = (a, b) => b ? gcd(b, a % b) : a;
    let gcd_ = values[0];
    let pairwise = true;
    for (let i = 0; i < values.length; i++) {
        if(values[i] <= 1){
            gcd_ = 1;
            continue;
        }
        if(prims[values[i] - 2] == -1 || prims[prims[values[i] - 2] - 2] == -1){
            pairwise = false;
        }else{
            prims[prims[values[i] - 2] - 2] = -1;
        }
        gcd_ = gcd(gcd_, values[i]);
    }
    if(pairwise){
        console.log('pairwise coprime');
    }else if(gcd_ === 1){
        console.log('setwise coprime');
    }else{
        console.log('not coprime');
    }
})();


(async () => {
    let input = '';
    for await (const chunk of process.stdin) input += chunk;
    let values = input.split(/\s/).map(v => +v);

    const n = values.shift();
    values = values.slice(0, n);
    values = values.sort((a, b) => b - a);

    let prims = [2];
    for(let i = 3; i <= values[0]; i++){
        const prim = prims.find((prim) => i % prim === 0)
        if(prim == undefined){
            prims.push(i);
        }else{
            prims.push(prim);
        }
    }

    const gcd = (a, b) => b ? gcd(b, a % b) : a;
    let gcd_ = values[0];
    for (let i = 0; i < values.length; i++) {
        if(prims[values[i] + 2] == -1){
            console.log('pairwise coprime');
            return;
        }
        prims[values[i]] = -1;
        gcd_ = gcd(gcd_, values[i]);
    }
    if(gcd_ === 1){
        console.log('setwise coprime');
    }else{
        console.log('not coprime');
    }
})();


function Main(input) {

    input = input.split("\n");

    N = Number(input[0]);
    let An = input[1].split(" ").map(Number);

    if (gcd(An) !== 1) {
        console.log("not coprime");
        return;
    }

    let freq = Array(1000001).fill(0);
    for(let A of An) {
        if (A === 1) continue;
        freq[A]++;
        if (freq[A] > 1) {
            console.log("setwise coprime");
            return;
        }
    }

    for (let i = 2; i <= 1000001; i++) {
        let tmp = 0;
        for (let j = i; j <= 1000001; j += i) {
            tmp += freq[j];
            if (tmp >= 2) {
                console.log("setwise coprime");
                return;
            }
        }
    }

    console.log("pairwise coprime");

}

function gcd(arg) {

    let f = (a, b) => b ? f(b, a % b) : a
    let ans = arg[0];
    for (let i = 1; i < arg.length; i++) {
        ans = f(ans, arg[i]);
    }
    return ans;

}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {

    input = input.split("\n");

    N = Number(input[0]);
    let An = input[1].split(" ").map(Number);

    /*if (gcd(...An) !== 1) {
        console.log("not coprime");
        return;
    }

    let freq = Array(1000001).fill(0);
    for(let A of An) {
        if (A === 1) continue;
        freq[A]++;
        if (freq[A] > 1) {
            console.log("setwise coprime");
            return;
        }
    }

    for (let i = 2; i <= 1000001; i++) {
        let tmp = 0;
        for (let j = i; j <= 1000001; j += i) {
            tmp += freq[j];
            if (tmp >= 2) {
                console.log("setwise coprime");
                return;
            }
        }
    }

    console.log("pairwise coprime");*/

}

function gcd(...arg) {

    var f = (a, b) => b ? f(b, a % b) : a
    var ans = arg[0]
    for (var i = 1; i < arg.length; i++) {
        ans = f(ans, arg[i]);
    }
    return ans;

}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function getFactors(num) {
    const maxFactorNum = Math.floor(Math.sqrt(num));
    const factorArr = [];
    let count = 0;  //count of factors found < maxFactorNum.

    for (let i = 1; i <= maxFactorNum; i++) {
        //inserting new elements in the middle using splice
        if (num % i === 0) {
            factorArr.push(i);
            let otherFactor = num / i; //the other factor
            if (i != otherFactor) {
                //insert these factors in the front of the array
                factorArr.push(otherFactor);
            }
            count++;
        }
    }

    return factorArr;
}

const processData = (lines) => {
    const nums = lines[1].split(' ').map( x => +x)

    let numMap = {}
    let cache = {}

    for (const d of nums) {
        const factors = cache[d] || getFactors(d, cache)
        cache[d] = factors
        for (const f of factors) {
            numMap[f] = numMap[f] ? numMap[f] + 1 : 1
        }
    }

    let max = 1

    for (let p in numMap) {
        if (p != '1') {
            max = Math.max(max, numMap[p])
        }
    }

    console.log(max === 1 ? 'pairwise coprime' : (max === nums.length ? 'not coprime' : 'setwise coprime'))
}

let i = ''
process.stdin.on('data', c => i += c)
process.stdin.on('end', () => {
    const {EOL} = require('os')
    const lines = i.split(EOL) /*your input text, split by lines*/
    processData(lines)
})


function Main(input) {
	input = input.trim().split("\n").map(function(x) { return x.split(" ")});
	let N = parseInt(input[0][0], 10);
	let A = input[1].map(e => parseInt(e, 10));
	let Amap = Array.from({length: 1e6 + 1}, () => false);
	let ansFlag0 = false;
	let N2 = N;
	let variation = 0;
	for (let i = 0; i < N; i++){
		if (Amap[A[i]]){
			if (A[i] !==1) ansFlag0 = true;
			N2 --;
			continue;
		}
		Amap[A[i]] = true;
		variation ++;
	}

	let bitmap = Array.from({length: 1e6 + 1}, () => false);
	bitmap[0] = true;
	bitmap[1] = true;

	// let ansFlag1 = false;
	let countList = [];
	for (let i = 2; i < bitmap.length; i++){
		if (bitmap[i]) continue;
		let count = 0;
		let j = 1;
		if (Amap[i * j]){
			count ++;
		}
		for (j = 2; j <= (1e6 / i); j++){
			bitmap[i * j] = true;
			if (Amap[i * j]){
				count ++;
			}

		}
		countList.push(count);
	}
	countList.sort((a,b) => a - b);
	let ans = "pairwise coprime";
	if (ansFlag0) ans = "setwise coprime";
	for (let i = 0; i < countList.length; i++){
		if (countList[i] <= 1) continue;
		if(countList[countList.length - 1] < N2){
			ans = "setwise coprime";
		} else {
			ans = "not coprime";
		}
	}
	if (variation === 1){
		if (A[0] === 1) ans = "pairwise coprime";
		else ans = "not coprime";
	}
	console.log(ans);

}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextssort(n,a){return a?cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>b-a):cin.slice(cid,cid+=n).map(a=>+a).sort((a,b)=>a-b);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

function gcd(a,b){return b?gcd(b,a%b):a;}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  var n = next();
  var a = nexts(n);
  var b = xArray(0,1e6+1);
  var f = 1;
  for(var i = 0; i < n && f; i++){
    var t = a[i];
    for(var j = 2; j*j <= t; j++){
      if(t%j === 0){
        if(b[j]){
          f = 0;
          break;
        }
        b[j] = 1;
        while(t%j === 0)t /= j;
      }
    }
    if(t > 1){
      if(b[t]){
        f = 0;
      }else{
        b[t] = 1;
      }
    }
  }
  if(f)return "pairwise coprime";
  t = a[0];
  for(var i = 1; i < n; i++){
    t = gcd(t,a[i]);
    if(t === 1)return "setwise coprime";
  }
  return "not coprime";
}


(async () => {
    let input = '';
    for await (const chunk of process.stdin) input += chunk;
    const lines = input.split(/\n/);
    const [h, w, m] = lines[0].split(/\s/).map(v => +v);
    const targets = lines.slice(1, m + 1).map(line => line.split(/\s/).map(v => v - 1));

    let targetCount = [new Array(h).fill(0), new Array(w).fill(0)];
    let targetMap = new Array(h).fill([]).map(x => new Array(w).fill(false));
    for (const target of targets) {
        targetCount[0][target[0]]++;
        targetCount[1][target[1]]++;
        targetMap[target[0]][target[1]] = true;
    }
    const xMax = targetCount[0].slice().sort((a, b) => b - a);
    const yMax = targetCount[1].slice().sort((a, b) => b - a);

    let yMaxs = [];
    for (let i = 0; i < h; i++) {
        if(targetCount[1][i] == yMax[0]){
            yMaxs.push(i);
        }
    }
    let allCross = 1;
    for (let i = 0; i < h && allCross; i++) {
        if(targetCount[0][i] == xMax[0]){
            for (let j = 0; j < yMaxs.length; j++) {
                if(!targetMap[i][yMaxs[j]]){
                    allCross = 0;
                    break;
                }
            }
        }
    }
    console.log(yMax[0] + xMax[0] - allCross);
})();

Score : 500 points

Problem Statement

We have a two-dimensional grid with H \times W squares. There are M targets to destroy in this grid - the position of the i-th target is \left(h_i, w_i \right).

Takahashi will choose one square in this grid, place a bomb there, and ignite it. The bomb will destroy all targets that are in the row or the column where the bomb is placed. It is possible to place the bomb at a square with a target.

Takahashi is trying to maximize the number of targets to destroy. Find the maximum number of targets that can be destroyed.

Constraints

All values in input are integers.

1 \leq H, W \leq 3 \times 10^5

1 \leq M \leq \min\left(H\times W, 3 \times 10^5\right)

1 \leq h_i \leq H

1 \leq w_i \leq W

\left(h_i, w_i\right) \neq \left(h_j, w_j\right) \left(i \neq j\right)

Input

Input is given from Standard Input in the following format:

H W M
h_1 w_1
\vdots
h_M w_M

Output

Print the answer.

Sample Input 1

2 3 3
2 2
1 1
1 3

Sample Output 1

3

We can destroy all the targets by placing the bomb at \left(1, 2\right).

Sample Input 2

3 3 4
3 3
3 1
1 1
1 2

Sample Output 2

3

Sample Input 3

5 5 10
2 5
4 3
2 3
5 5
2 2
5 4
5 3
5 1
3 5
1 4

Sample Output 3

6


const main = (input) => {
  input = input.trim().split('\n')
  const [h, w, m] = input[0].split(' ').map(Number)

  const hs = new Array(h+1).fill(0)
  const ws = new Array(w+1).fill(0)
  const bomb = new Map()

  for (let i=1; i<=m; i++) {
    const [hi, wi] = input[i].split(' ').map(Number)
    hs[hi-1]++
    ws[wi-1]++
    bomb.set(`${hi-1}:${wi-1}`, true)
  }

  const hmx = Math.max(...hs)
  const wmx = Math.max(...ws)

  let topH = []
  let topW = []
  for (let i=0; i<Math.max(hs.length, ws.length); i++) {
    if (hs[i] && hs[i] === hmx) topH = [...topH, [i, hmx]]
    if (ws[i] && ws[i] === wmx) topW = [...topW, [i, wmx]]
  }

  // const hs = {}
  // const ws = {}
  //
  // const bomb = new Map()
  //
  // for (let i=1; i<=m; i++) {
  //   const [hi, wi] = input[i].split(' ').map(Number)
  //   hs[hi-1] = ~~hs[hi-1] + 1
  //   ws[wi-1] = ~~ws[wi-1] + 1
  //   bomb.set(`${hi-1}:${wi-1}`, true)
  // }

  // const ascH = [...Object.entries(hs)].sort((a, b) => b[1] - a[1])
  // const ascW = [...Object.entries(ws)].sort((a, b) => b[1] - a[1])
  //
  // const topH = [ascH.shift()]
  // const topW = [ascW.shift()]
  // while (ascH[0] && topH[0][1] === ascH[0][1]) topH.push(ascH.shift())
  // while (ascW[0] && topW[0][1] === ascW[0][1]) topW.push(ascW.shift())

  for (let x=0; x<topH.length; x++) {
    for (let y=0; y<topW.length; y++) {
      if (!bomb.has(`${topH[x][0]}:${topW[y][0]}`)) return console.log(hmx + wmx)
    }
  }

  return console.log(hmx + wmx - 1)
  // return console.log(topH[0][1] + topW[0][1] - 1)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


const main = (input) => {
  input = input.trim().split('\n')
  const [h, w, m] = input[0].split(' ').map(Number)

  const hs = {}
  const ws = {}

  const bomb = new Map()

  for (let i=1; i<=m; i++) {
    const [hi, wi] = input[i].split(' ').map(Number)

    hs[hi-1] = ~~hs[hi-1] + 1
    ws[wi-1] = ~~ws[wi-1] + 1

    bomb.set(`${hi-1}:${wi-1}`, true)
  }

  const ascH = [...Object.entries(hs)].sort((a, b) => b[1] - a[1])
  const ascW = [...Object.entries(ws)].sort((a, b) => b[1] - a[1])

  const topH = [ascH.shift()]
  while (ascH[0] && topH[0][1] === ascH[0][1]) topH.push(ascH.shift())
  const topW = [ascW.shift()]
  while (ascW[0] && topW[0][1] === ascW[0][1]) topW.push(ascW.shift())

  // console.log(bomb.entries())
  // console.log(topH, topW)

  for (let x=0; x<topH.length; x++) {
    for (let y=0; y<topW.length; y++) {
      if (!bomb.has(`${topH[x][0]}:${topW[y][0]}`)) return console.log(topH[0][1] + topW[0][1])
    }
  }

  return console.log(topH[0][1] + topW[0][1] - 1)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


function main(input = "") {
    const lines = input.split("\n");
    const header = lines[0].split(" ").map((v) => (Number(v)));
    const H = header[0], W = header[1], M = header[2];

    let arrH = new Int32Array(H);
    let arrW = new Int32Array(W);
    let grid = new Set();
    for (let i = 0; i < M; i++) {
        let arr = lines[i + 1].split(" ");
        let h = arr[0] - 1, w = arr[1] - 1;
        arrH[h]++;
        arrW[w]++;
        grid.add(h * W + w);
    }

    let maxH = arrH[0];
    let idsH = [0];
    for (let i = 0; i < H; i++) {
        let v = arrH[i];
        if (maxH < v) {
            maxH = v;
            idsH = [i]
        } else if (maxH === v) {
            idsH.push(i);
        }
    }

    let maxW = arrW[0];
    let idsW = [0];
    for (let i = 0; i < W; i++) {
        let v = arrW[i];
        if (maxW < v) {
            maxW = v;
            idsW = [i]
        } else if (maxW === v) {
            idsW.push(i);
        }
    }

    for (let h = 0; h < idsH.length; h++) {
        let idh = idsH[h];
        for (let w = 0; w < idsW.length; w++) {
            let idw = idsW[w];
            if (!grid.has(idh * W + idw)) {
                return maxH + maxW;
            }
        }
    }

    return maxH + maxW - 1;
}

//******************************
exports.main = main;

function Main(input) {
    console.log(main(input.trim()));
}

if (process.argv[2] !== "test") {
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}


function main(input = "") {
    const lines = input.split("\n");
    const header = lines[0].split(" ").map((v) => (Number(v)));
    const H = header[0], W = header[1], M = header[2];

    let arrH = new Int32Array(H);
    let arrW = new Int32Array(W);
    let grid = new Set();
    for (let i = 0; i < M; i++) {
        let arr = lines[i + 1].split(" ").map((v) => (Number(v)));
        let h = arr[0] - 1, w = arr[1] - 1;
        arrH[h]++;
        arrW[w]++;
        grid.add(h * W + w);
    }

    let maxH = arrH[0];
    let maxHids = [0];
    for (let i = 0; i < H; i++) {
        let v = arrH[i];
        if (maxH < v) {
            maxH = v;
            maxHids.length = 0;
            maxHids.push(i);
        } else if (maxH === v) {
            maxHids.push(i);
        }
    }

    let maxW = arrW[0];
    let maxWids = [0];
    for (let i = 0; i < W; i++) {
        let v = arrW[i];
        if(maxW < v){
            maxW = v;
            maxWids.length = 0;
            maxWids.push(i);
        } else if ( maxW === v){
            maxWids.push(i);
        }
    }

    let maxCnt = -1;
    for (let h = 0; h < maxHids.length; h++) {
        let idh = maxHids[h];
        for (let w = 0; w < maxWids.length ; w++) {
            let idw = maxWids[w];
            let id = idh * W + idw;
            let cnt = maxH + maxW - (grid.has(id) ? 1 : 0);
            if (maxCnt < cnt) {
                maxCnt = cnt;
            }
        }
    }

    return maxCnt;
}

//******************************
exports.main = main;

function Main(input) {
    console.log(main(input.trim()));
}

if (process.argv[2] !== "test") {
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}


const { format } = require('path')

// let input = require('fs').readFileSync('/dev/stdin', 'utf8')
let input = require('fs').readFileSync('./sample_e.txt', 'utf8')
.split(/\n| /)
// .map(item => parseInt(item))
.slice(0,-1)

const [height, width, ..._targets] = input
const targets = _targets.slice(1)
let numMap = []

// Map作成
for(let i=0; i<height; i++){
    numMap.push([])
    for(let j=0; j<width; j++){
        numMap[i].push(0)
    }
}

const leng = targets.length / 2
for(let i=0; i<leng; i++){
    const [_Y, _X] = targets.slice(2*i, 2*i+2)
    const Y = _Y - 1
    const X = _X - 1
    for(let j=0; j<width; j++){
        numMap[Y][j] += 1
    }
    for(let j=0; j<height; j++){
        numMap[j][X] += 1
    }
    numMap[Y][X] -= 1
}

let Max = 0
for(let i=0; i<height; i++){
    for(let j=0; j<width; j++){
        if(Max < numMap[i][j]) Max = numMap[i][j]
    }
}

console.log(Max)


console.log((args=>{
  const [[H,W,M],...target] = args.trim().split`\n`.map(r=>r.split` `.map(v=>v|0));
  const b = Array.from({length:H},_=>Array(W).fill(false));
  const bR = Array(H).fill(0);
  const bC = Array(W).fill(0);
  let xR = 0, xC = 0;
  for ( const [h,w] of target ) {
    b[h-1][w-1] = true;
    xR = Math.max(xR,++bR[h-1]);
    xC = Math.max(xC,++bC[w-1]);
  }
  const hR = [], hC = [];
  for ( let i = 0; i < H; i++ ) if ( bR[i] === xR ) hR.push(i);
  for ( let j = 0; j < W; j++ ) if ( bC[j] === xC ) hC.push(j);
  for ( const h of hR ) {
    for ( const w of hC ) {
      if ( !b[h][w] ) return xR+xC;
    }
  }
  return xR+xC-1;
})(require('fs').readFileSync('/dev/stdin','utf8')));


'use strict';

function Main(input) {
    //H W M
    // (hi, wi)
    const tmp = input.trim().split('\n');
    const [H, W, M] = tmp
        .shift()
        .split(' ')
        .map((v) => Number(v));
    const hw = tmp.map((v) => v.split(' ').map((v) => Number(v)));
    // console.log(H, W, M, hw);

    // Hの最大値
    let arr = Array(H + 1).fill(0);
    for (const v of hw) {
        arr[v[0]] += 1;
    }
    const hmax = arr.reduce((a, b) => Math.max(a, b));
    let harr = [];
    arr.forEach((v, i) => {
        if (v === hmax) harr.push(i);
    });

    // Hの最大値それぞれについてのWの最大値
    let wmax = 0;
    for (const value of harr) {
        const newhw = hw.filter((v) => v[0] !== value);
        let arr = Array(W + 1).fill(0);
        for (const v of newhw) {
            arr[v[1]] += 1;
        }
        const wtmp = arr.reduce((a, b) => Math.max(a, b));
        if (wtmp > wmax) {
            wmax = wtmp;
        }
    }

    console.log(hmax + wmax);

    return;
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input = require("fs").readFileSync("/dev/stdin", "utf8")
const lines = input.split('\n')
let [H, W, M] = lines[0].split(' ').map(Number)

const h = Array(H + 1).fill(0)
const w = Array(W + 1).fill(0)

const map = Array(H + 1).fill().map(_ => Array(W + 1).fill(0))

for (let i = 1; i <= M; i++) {
    const p = lines[i].split(' ').map(Number)
    h[p[0]]++
    w[p[1]]++
    map[p[0]][p[1]] = 1
}

const hm = h.reduce((a, b) => {
    return a > b ? a : b
})
const hp = []
h.forEach((a, i) => {
    if (a === hm) {
        hp.push(i)
    }
})

const wm = w.reduce((a, b) => {
    return a > b ? a : b
})
const wp = []
w.forEach((a, i) => {
    if (a === wm) {
        wp.push(i)
    }
})

let c = 1
for (let i = 0; i < hp.length; i++) {
    for (let j = 0; j < wp.length; j++) {
        if (!map[hp[i]][wp[j]]) {
            c = 0
            break
        }
    }
    if (c === 0) break
}

console.log(hm + wm - c)


function main(input = "") {
    let N = 0 | input;
    res = N % 1000;
    if ( res > 0){
        return 1000 - res;
    } else {
        return 0;
    }
}

//******************************
exports.main = main;

function Main(input) {
    console.log(main(input.trim()));
}

if (process.argv[2] !== "test") {
    Main(require("fs").readFileSync("/dev/stdin", "utf8"));
}

Score : 100 points

Problem Statement

We will buy a product for N yen (the currency of Japan) at a shop.

If we use only 1000-yen bills to pay the price, how much change will we receive?

Assume we use the minimum number of bills required.

Constraints

1 \leq N \leq 10000

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the amount of change as an integer.

Sample Input 1

1900

Sample Output 1

100

We will use two 1000-yen bills to pay the price and receive 100 yen in change.

Sample Input 2

3000

Sample Output 2

0

We can pay the exact price.


function main(input){
	const N = parseInt(input, 10)
    const r = N % 1000
    console.log(r === 0 ? r : 1000 - r)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


function Main(input) {
	let input = parseint(input);
	for(let i=0; i*1000<input;i++){}

  	console.log('%d',i*1000-input);
}

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


const main = async () => {
  const input = require('fs').readFileSync('/dev/stdin', 'UTF-8').trim()

const num = parseInt(input).toLocaleString().split(',')
const answer = 1000 - parseInt(num[num.length - 1])

if (answer === 1000) {
  console.log('0');

} else {
  console.log(answer);

}
}

main()


const main = async () => {
  const input = require('fs').readFileSync('/dev/stdin', 'UTF-8').trim()

const num = parseInt(input).toLocaleString().split(',')
const answer = 1000 - parseInt(num[num.length - 1])

if (answer === 1000) {
  console.log('1000');

} else {
  console.log(answer);

}
}

main()


const main = async () => {
  const input = require('fs').readFileSync('/dev/stdin', 'UTF-8').trim()
  const n = input
  const bill = 1000
  const mod = n % bill
  const change = (bill - mod) % bill

  console.log(change)
}

main()


function Main(input) {
    var payment = parseInt(input);
    if (payment % 1000 == 0) {
        console.log(0);
    } else {
        console.log(1000 - payment % 1000);
    }
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


process.stdin.resume();
process.stdin.setEncoding('utf8');

var input_lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

reader.on('line', (line) => {
  input_lines.push(line)
})

reader.on('close', () => {
  value = parseInt(input_lines[0])
  while (value - 1000 > 0) {
    value = value - 1000;
  }
  console.log(1000 - value)
})


consot n = Number(require('fs').readFileSync('/dev/stdin', 'utf8'))
console.log(1000 - n % 1000)


function Main(input) {
	input = input.split("\n");

	var n = parseInt(input[0], 10);

	var result = n
	for (var i = 1; i < 11; i++) {
	if  (result < 1000) {
	break;
	} else {
	result = result - 1000;
	}
	}

	result = 1000 - result

	console.log(result);
	}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input) {
  const inputs =input.split('\n')
  const [N] = inputs[0].split(' ')
  if (N % 1000 === 0) {
    console.log(0)
  } else {
    console.log(
      (1000 - (N % 1000))
    )
  }
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim())


function Main(input) {
	input = input.split("\n");

	var n = parseInt(input[0], 10);

	var result = n
	for (var i = 1; i < 11; i++) {
	if  (result < 1000) {
	break;
	} else {
	result = result - 1000;
	}
	}

	console.log(result);
	}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


// inputに入力データ全体が入る
function Main(input) {
  // 1行目がinput[0], 2行目がinput[1], …に入る
  input = input.trim().split("\n");
  // const [X] = input[0].split(" ").map((n) => parseInt(n));
  n = parseInt(input[0]) % 1000

  //出力
  console.log(n);
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
// Main(require("fs").readFileSync("/dev/stdin", "utf8"));
Main(require("fs").readFileSync("./input.txt", "utf-8"));


function main(lines) {
  const N = +lines[0];

  let res;

  for (let i = 1000; i <= 10000; i += 1000) {
    if (i >= N) {
      res = i - N;
      break;
    }
  }

  console.log(res);
}

main( require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n") );

function splitN(s) {
  return s.split(' ').map(Number);
}


function Main(input) {
  const num = parseInt(input);
  console.log(1000 - (num%1000));
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function Main(input) {
    input = input.trim().split("\n").map(function(x) { return x.split(" ")});
    var N = parseInt(input[0][0], 10);
    ans = Math.ceil(N / 1000) * 1000 - N;
    console.log(ans);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict";
var input=require("fs").readFileSync("/dev/stdin","utf8");
var cin=input.split(/ |\n/),cid=0;
function next(){return +cin[cid++];}
function nextstr(){return cin[cid++];}
function nextbig(){return BigInt(cin[cid++]);}
function nexts(n,a){return a?cin.slice(cid,cid+=n):cin.slice(cid,cid+=n).map(a=>+a);}
function nextm(h,w,a){var r=[],i=0;if(a)for(;i<h;i++)r.push(cin.slice(cid,cid+=w));else for(;i<h;i++)r.push(cin.slice(cid,cid+=w).map(a=>+a));return r;}
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill().map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill().map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(String(myOut));

function main(){
  var n = next();
  return (1000-n%1000)%1000;
}


var toInt = x=>parseInt(x,10);
var toIntArr = arr=>arr.map(x=>toInt(x));
var abs = x=>x>0?x:-x;
function min(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]<val)val = rest[i];return val}
function max(){var rest = arguments,val=rest[0];for(var i=1;i<rest.length;i++)if(rest[i]>val)val = rest[i];return val}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

function Main(input){
	var input = input.split('\n');
	input = input.map(e => toIntArr(e.split(' ')));
	var d = input[0][0];
	var cs = input[1];
	var ss = input.slice(2);
	//var ts = input.slice(d+2).map(e=>e[0]);

	var score = 0;
	var ans = [];
	let type;
	var lastday = [];
	lastday.length = 26;
	lastday.fill(-1);

	//let scoreDay = [];

	//day(0~25)にtype(1~26)を選んだ場合の満足度の変化(lastdayのdayは0~)
	function getScore(day,type){
		let ans = 0;
		ans += ss[day][type-1];
		for(let t = 0; t < 26; t++){
			if(t!==type-1) ans -= cs[t] * (day - lastday[t]);
		}
		return ans;
	}

	var tempScore = [];
	let maxType = 1;
	for(let i = 0; i < d; i++){
	tempScore.fill(0);

		for(j = 0; j < 26; j++){
			tempScore[j] = getScore(i,j+1);
		}
		maxType = tempScore.indexOf(Math.max(...tempScore)) +1; //0~25 +1

		type = maxType;
		ans.push(type);
		lastday[type-1] = i;

		score += tempScore[type];

		//scoreDay[i] = score;

	}

	console.log(ans.join('\n'));
}

Problem Statement

AtCoder currently hosts three types of contests: ABC, ARC, and AGC. As the number of users has grown, in order to meet the needs of more users, AtCoder has decided to increase the number of contests to 26 types, from AAC to AZC. For convenience, we number these 26 types as type 1 through type 26. AtCoder wants to schedule contests for D days so that user satisfaction is as high as possible. For every day, AtCoder will hold exactly one contest, and each contest will end on that day. The satisfaction is calculated as follows.

The satisfaction at the beginning of day 1 is 0. Satisfaction can be negative.

Holding contests increases satisfaction. The amount of increase will vary depending on a variety of factors. Specifically, we know in advance that holding a contest of type i on day d will increase the satisfaction by s_{d,i}.

If a particular type of contest is not held for a while, the satisfaction decreases. Each contest type i has an integer c_i, and at the end of each day d=1,2,...,D, the satisfaction decreases as follows. Let \mathrm{last}(d,i) be the last day before day d (including d) on which a contest of type i was held. If contests of type i have never been held yet, we define \mathrm{last}(d,i)=0. At the end of day d, the satisfaction decreases by \sum _{i=1}^{26}c_i \times (d-\mathrm{last}(d,i)).

Please schedule contests on behalf of AtCoder.
If the satisfaction at the end of day D is S, you will get a score of \max(10^6 + S, 0).
There are 50 test cases, and the score of a submission is the total scores for each test case.
You can make submissions multiple times, and the highest score among your submissions will be your score.

Constraints

D = 365

Each c_i is an integer satisfying 0\leq c_i \leq 100.

Each s_{d,i} is an integer satisfying 0\leq s_{d,i} \leq 20000.

Input

Input is given from Standard Input in the following format:

D
c_1 c_2 \cdots c_{26}
s_{1,1} s_{1,2} \cdots s_{1,26}
\vdots
s_{D,1} s_{D,2} \cdots s_{D,26}

Output

Let t_d (1\leq t_d \leq 26) be the type of the contest that will be held at day d.
Print D integers t_d to Standard Output in the following format:

t_1
t_2
\vdots
t_D

Any output that does not follow the above format may result in 0 pointsWA for that test case.

Input Generation

Each integer c_i and s_{d,i} is generated independently and uniformly at random from the integers in the range described in the problem statement.

Sample Input 1

5
86 90 69 51 2 96 71 47 88 34 45 46 89 34 31 38 97 84 41 80 14 4 50 83 7 82
19771 12979 18912 10432 10544 12928 13403 3047 10527 9740 8100 92 2856 14730 1396 15905 6534 4650 11469 3628 8433 2994 10899 16396 18355 11424
6674 17707 13855 16407 12232 2886 11908 1705 5000 1537 10440 10711 4917 10770 17272 15364 19277 18094 3929 3705 7169 6159 18683 15410 9092 4570
6878 4239 19925 1799 375 9563 3445 5658 19857 11401 6997 6498 19933 3848 2426 2146 19745 16880 17773 18359 3921 14172 16730 11157 5439 256
8633 15862 15303 10749 18499 7792 10317 5901 9395 11433 3514 3959 5202 19850 19469 9790 5653 784 18500 10552 17975 16615 7852 197 8471 7452
19855 17918 7990 10572 4333 438 9140 9104 12622 4985 12319 4028 19922 12132 16259 17476 2976 547 19195 19830 16285 4806 4471 9457 2864 2192

Sample Output 1

1
17
13
14
13

Note that this example is a small one for checking the problem specification. It does not satisfy the constraint D=365 and is never actually given as a test case. The final satisfaction with this output is 79325, so the score is 1079325.

Input generator, score calculator, and visualizer

Beginner's Guide

If you don't know what to do, proceed to problem B or C.


'use strict'

function main(input) {
  const inputRows = input.split('\n');
  const d = parseInt(inputRows[0])
  let cStrArray = inputRows[1].split(' ')
  const c = cStrArray.map(str => parseInt(str))
  let s = []
  for (let i = 2; i < inputRows.length; i++) {
    s.push([])
    const tmpRow = inputRows[i].split(' ')
    for (let j = 0; j < tmpRow.length; j++) {
      s[i - 2].push(parseInt(tmpRow[j]))
    }
  }

  let t = []

  for (let i = 0; i < s.length; i++) {
    let tmpMax = s[i][0]
    let index = 0
    for (let j = 1; j < s[i].length; j++) {
      if (s[i][j] > tmpMax) {
        index = j
        tmpMax = s[i][j]
      }
    }
    t.push(index + 1)
  }

  console.log(t)
}

main(require("fs").readFileSync("/dev/stdin", "utf8"));

main(input)


const main = (input) => {
  input = input.trim().split('\n')
  const [n, m, k] = input[0].split(' ').map(BigInt)
  const a = input[1].split(' ').map(BigInt)
  const b = input[2].split(' ').map(BigInt)

  let ans = 0

  const a_read = [], b_read = []
  let a_sum = 0n, b_sum = 0n

  for (let i=0; i<b.length; i++) {
    if (b_sum + b[i] <= k) {
      b_read.push(b[i])
      b_sum += b[i]
    }
    else break
  }

  for (let i=0; i<a.length; i++) {
    a_read.push(a[i])
    a_sum += a[i]

    while (a_sum + b_sum > k && b_read.length) b_sum -= b_read.pop()

    if (a_sum + b_sum > k) break

    ans = Math.max(ans, a_read.length + b_read.length)
  }

  return console.log(ans)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))

Score : 300 points

Problem Statement

We have two desks: A and B. Desk A has a vertical stack of N books on it, and Desk B similarly has M books on it.

It takes us A_i minutes to read the i-th book from the top on Desk A (1 \leq i \leq N), and B_i minutes to read the i-th book from the top on Desk B (1 \leq i \leq M).

Consider the following action:

Choose a desk with a book remaining, read the topmost book on that desk, and remove it from the desk.

How many books can we read at most by repeating this action so that it takes us at most K minutes in total? We ignore the time it takes to do anything other than reading.

Constraints

1 \leq N, M \leq 200000

1 \leq K \leq 10^9

1 \leq A_i, B_i \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M K
A_1 A_2 \ldots A_N
B_1 B_2 \ldots B_M

Output

Print an integer representing the maximum number of books that can be read.

Sample Input 1

3 4 240
60 90 120
80 150 80 150

Sample Output 1

3

In this case, it takes us 60, 90, 120 minutes to read the 1-st, 2-nd, 3-rd books from the top on Desk A, and 80, 150, 80, 150 minutes to read the 1-st, 2-nd, 3-rd, 4-th books from the top on Desk B, respectively.

We can read three books in 230 minutes, as shown below, and this is the maximum number of books we can read within 240 minutes.

Read the topmost book on Desk A in 60 minutes, and remove that book from the desk.

Read the topmost book on Desk B in 80 minutes, and remove that book from the desk.

Read the topmost book on Desk A in 90 minutes, and remove that book from the desk.

Sample Input 2

3 4 730
60 90 120
80 150 80 150

Sample Output 2

7

Sample Input 3

5 4 1
1000000000 1000000000 1000000000 1000000000 1000000000
1000000000 1000000000 1000000000 1000000000

Sample Output 3

0

Watch out for integer overflows.


const main = async () => {
  'use strict'
  const input = require('fs').readFileSync('/dev/stdin', 'UTF-8').trim()

  let setting = input.split('\n')

  const setting_1 = setting[0].split(' ')
  const setting_2 = setting[1].split(' ').map( str => parseInt(str, 10) )
  const setting_3 = setting[2].split(' ').map( str => parseInt(str, 10) )

  const a_table_book = setting_1[0] - 0
  const b_table_book = setting_1[1] - 0
  let time_sum = setting_1[2] - 0

  let count = 0

  let book_arr = setting_2.concat(setting_3)
  book_arr.sort(function(a,b){
    if( a < b ) return -1;
    if( a > b ) return 1;
    return 0;
  });

  while (time_sum > 0 || book_arr.length > 0) {
    if (time_sum >= book_arr[0]) {
      time_sum -= book_arr[0]
      book_arr.shift()
      count++
    } else {
      break
    }
  }

  console.log(count)

}

main()


const readLines = (input) => input.split('\n')
const println = (value) => console.log(value)
const readInt = (input) => parseInt(input, 10)
const readIntList = (input) => input.split(' ').map(n => parseInt(n, 10))
const naturalOrder = (a, b) => {
    if (b == a) return 0
    return (a < b) ? -1 : 1
}

function main(input) {
    const lines = readLines(input)
    const [n, m, k] = readIntList(lines[0])
    const aArray = readIntList(lines[1]).sort(naturalOrder)
    const bArray = readIntList(lines[2]).sort(naturalOrder)

    let aSum = aArray.reduce((acc, a) => acc + a)
    let bSum = bArray.reduce((acc, b) => acc + b)
    let nonReadCount = 0
    let ai = aArray.length - 1
    let bi = bArray.length - 1
    while (aSum + bSum > k) {
        if (ai < 0 && bi < 0) {
            break
        }

        nonReadCount++

        if (ai < 0) {
            bSum -= bArray[bi]
            bi--
            continue
        } else if (bi < 0) {
            aSum -= aArray[ai]
            ai--
            continue
        }

        if (aArray[ai] < bArray[bi]) {
            bSum -= bArray[bi]
            bi--
        } else {
            aSum -= aArray[ai]
            ai--
        }
    }
    println(aArray.length + bArray.length - nonReadCount)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


process.stdin.resume();
process.stdin.setEncoding('utf8');

var input_lines = [];
var reader = require('readline').createInterface({
  input: process.stdin,
  output: process.stdout
});

var row = 0
reader.on('line', (line) => {
  var column = line.split(" ")
  var new_input_lines = []
  for(var i=0;i<column.length;i++){
      new_input_lines[i] = parseInt(column[i]);
  }
  input_lines.push(new_input_lines)
});

reader.on('close', () => {
  //console.log(input_lines);
  var a_book = input_lines[1], a_turn = 0;
  var b_book = input_lines[2], b_turn = 0;
  var total_time = input_lines[0][2];
  var sum_time = 0;
  var sum_book = 0;

  while(true){
    //console.log("A = " + a_book[a_turn]);
    //console.log("B = " + b_book[b_turn]);
    if(a_book[a_turn] != null && b_book[b_turn] != null){
      if(a_book[a_turn] <= b_book[b_turn]){
        sum_time += a_book[a_turn];
        //console.log(sum_time);
        a_turn ++;
      } else {
        sum_time += b_book[b_turn];
        //console.log(sum_time);
        b_turn ++;
      }
    } else if(a_book[a_turn] != null && b_book[b_turn] == null){
      sum_time += a_book[a_turn];
      //console.log(sum_time);
      a_turn ++;
    } else if(a_book[a_turn] == null && b_book[b_turn] != null){
      sum_time += b_book[b_turn];
      //console.log(sum_time);
      b_turn ++;
    } else if(a_book[a_turn] == null && b_book[b_turn] == null){
      break;
    }

    if(sum_time <= total_time){
      sum_book ++;
    } else {
      break;
    }
  }

  console.log(sum_book);

});


function Main(input) {
    input = input.trim().split('\n');
    const k = parseInt(input[0].split(' ')[2], 10);
    const a = input[1].split(' ');
    const b = input[2].split(' ');

    let t = 0;
    for(let i=0; i<b.length; i++){
        t += parseInt(b[i], 10);
    }

    let j = b.length;
    let ans = 0;
    for(let i=0; i<=a.length; i++){
        while(j > 0 && t > k) {
            j--;
            t -= parseInt(b[j]);
        }
        if(t > k) break;
        if(ans < i+j) ans = i+j;
        if(i === a.length) break;
        t += parseInt(a[i], 10);
    }
    console.log(ans);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));


Main = input => {
  const [r1, r2, r3] = input.split("\n");
  const [n, m, k] = r1.split(" ").map(Number);
  const a = r2.split(" ").map(Number);
  const b = r3.split(" ").map(Number);
  // 読む冊数
  for (let i = 1; i <= n + m; i++) {
    // 読めるか
    let canRead = false;
    for (let ai = 0; ai <= i && !canRead; ai++) {
      // bの冊数
      const bi = i - ai;
      // aにかかる時間
      const atime = a.filter((v, j) => j < ai).reduce((x, y) => x + y, 0);
      // bにかかる時間
      const btime = b.filter((v, j) => j < bi).reduce((x, y) => x + y, 0);
      // 総計
      const alltime = atime + btime;
      // 読めるか判定
      if (alltime <= k) canRead = true;
    }
    // 読めなかったら終わり
    if (!canRead) {
      console.log(i - 1);
      break;
    }
    // 全部読めてもおわり
    if (canRead && i == n + m) {
      console.log(i);
      break;
    }
  }
};
 Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


function main(input) {
    const [n, m, k] = shaping(input[0]);
    const a = shaping(input[1]);
    const b = shaping(input[2]);
    if (a[0] > k && b[0] > k) { return console.log(0); };
    let timeA = [0];
    let timeB = [0];
    let sumTime = 0;
    let ans = [0];
    //必要最低限のAの累積和
    for (let i = 0; i < n; i++){
        sumTime += a[i];
            if (sumTime == k) {
                timeA.push(sumTime);
                break;
            } else if(sumTime > k){
                break;
            }
        timeA.push(sumTime);
    }
    sumTime = 0;
    for (let i = 0; i < m; i++){
        sumTime += b[i];
        if (sumTime == k) {
            timeB.push(sumTime);
            break;
        } else if (sumTime > k) {
            break;
        }
        timeB.push(sumTime);
    }
    let i = 0;
    let j = timeB.length-1;

    while (i < timeA.length) {
        while (j > -1) {
            if (timeB[j] <= k - timeA[i]) {
                ans.push(i + j);
                break;
            } else {
                j--;
            }
        }
        i++;
    }
    console.log(Math.max(...ans));
}

function shaping(arr) {
    return arr.split(' ').map(Number);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));


function main(input) {
    const [n, m, k] = shaping(input[0]);
    const a = shaping(input[1]);
    const b = shaping(input[2]);
    if (a[0] > k && b[0] > k) { return console.log(0); };
    let timeA = new Array();
    let timeB = new Array();
    let sumTime = 0;
    let ans = new Array();
    //必要最低限のAの累積和
    for (let i = 0; i < n; i++){
        sumTime += a[i];
        if (sumTime >= k) {
            if (sumTime = k) {
                ans.push(timeA.length);
                console.log(timeA.length);
                break;
            } else {
                ans.push(timeA.length - 1);
                break;
            }
        }
        timeA.push(sumTime);
    }
    sumTime = 0;
    for (let i = 0; i < m; i++){
        sumTime += b[i];
        if (sumTime >= k) {
            if (sumTime = k) {
                ans.push(timeB.length);
                break;
            } else {
                ans.push(timeB.length - 1);
                break;
            }
        }
        timeB.push(sumTime);
    }
    console.log(timeA);
    console.log(timeB);

    let i = 0;
    let j = timeB.length-1;

    while (i < timeA.length) {
        while (j > -1) {
            if (timeB[j] <= k - timeA[i]) {
                ans.push(i + j + 2);
                break;
            } else {
                j--;
            }
        }
        i++;
    }
    console.log(Math.max(...ans));
}

function shaping(arr) {
    return arr.split(' ').map(Number);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"));


//let input = "3 8 730\n60 90 120\n80 150 80 150 11 11 11 11 11";

function main(input){
	input = input.trim();
 	let N = parseInt(input.split("\n")[0].split(" ")[0]);
 	let M = parseInt(input.split("\n")[0].split(" ")[1]);
	let K = parseInt(input.split("\n")[0].split(" ")[2]);

	let nBooks = input.split("\n")[1].split(" ");
  	for(let i=0; i<nBooks.length; i++){nBooks[i] = parseInt(nBooks[i]);}
	let mBooks = input.split("\n")[2].split(" ");
  	for(let i=0; i<mBooks.length; i++){mBooks[i] = parseInt(mBooks[i]);}

 	function getRuiseki(books){
 	  	let ruiseki = 0;
		let Yomu = [];
  		for(let i=0; ruiseki<K; i++){
          ruiseki += books[i];
          Yomu.push(ruiseki);
        }
      	return(Yomu);
    }

	let nBooksKei = getRuiseki(nBooks);
	let mBooksKei = getRuiseki(mBooks);

  	if(nBooksKei[nBooksKei.length-1]>K){nBooksKei.pop();}
  	if(mBooksKei[mBooksKei.length-1]>K){mBooksKei.pop();}

  	nBooksKei.unshift(0);
  	mBooksKei.unshift(0);

  	// console.log(K);
	// console.log(nBooksKei);
 	// console.log(mBooksKei);

	let kiroku = 0;
 	let sinKiroku = 0;
  	let bestJ = M;
 	for(let i=0; nBooks[i] < K; i++){
      for(let j=bestJ; j>0; j--){
        if(nBooksKei[i] + mBooksKei[j] <= K){
          	kiroku = i + j;
          	bestJ = j;
          	// console.log(i + ":" + j);
        	if(kiroku>sinKiroku){sinKiroku=kiroku;}
            break;
        }
      }
    }
  	console.log(sinKiroku);
}//main(input);
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input){
	input = input.trim();
 	let N = parseInt(input.split("\n")[0].split(" ")[0]);
 	let M = parseInt(input.split("\n")[0].split(" ")[1]);
	let K = parseInt(input.split("\n")[0].split(" ")[2]);

	let nBooks = input.split("\n")[1].split(" ");
  	for(let i=0; i<nBooks.length; i++){nBooks[i] = parseInt(nBooks[i]);}
	let mBooks = input.split("\n")[2].split(" ");
  	for(let i=0; i<mBooks.length; i++){mBooks[i] = parseInt(mBooks[i]);}

	let kiroku = 0;
 	let sinKiroku = 0;
  	let nKei = 0;
  	let mKei = 0;
  	let goukei = 0;
  	nBooks.unshift(0);
    mBooks.unshift(0);

    //console.log(nBooks); console.log(mBooks);

  	for(let i=0; (nKei<=K && i<nBooks.length); i++){
      nKei += nBooks[i];
      goukei = nKei;
      for(let j=0; (goukei<=K && j<mBooks.length); j++){
        goukei += mBooks[j];
        if(goukei>K){break;}
        kiroku = i + j;
        console.log(goukei+" "+i+"("+nKei+") "+j+"("+(goukei-nKei)+") "+kiroku);
        if(kiroku>sinKiroku){sinKiroku=kiroku;}
      }
    }

  	console.log(sinKiroku);
}
//main(input);
main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input){
  input = input.split('\n');
  const [n, m, k] = input[0].split(' ').map(Number);
  const a = input[1].split(' ').map(Number).reduce((a, x)=>{
    if(a.length === 0){
      return [x];
    } else{
      a.push(x+a[a.length-1])
      return a;
    }
  },[]);
  const b = input[2].split(' ').map(Number).reduce((a, x)=>{
    if(a.length === 0){
      return [x];
    } else{
      a.push(x+a[a.length-1]);
      return a;
    }
  },[]);

  const aMax = searchIndex(a, k);

  let max = 0;
  for(let i=0; i<=aMax; i++){
    const ak = i===0? 0 : a[i-1];
    const bMax = searchIndex(b, k-ak);
    if(bMax + i > max){
      max = bMax + i;
    }
  }

  console.log(max);
}

function searchIndex(arr, k){
  let st = 0;
  let ed = arr.length;
  while(st != ed){
    i = ((st + ed)/2) >> 0;
    if(k < arr[i]) {
       ed = i;
    }else{
      st = i+1;
    }
  }

  return st;
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').trim());


  let input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n")
  let time = +input[0].split(" ")[2]
  let ATab = input[1].split(" ")
  let BTab = input[2].split(" ")
  let count = 0
  let cost = 0
  if (+time < +ATab[0] && +time < +BTab[0]) {
    console.log(count);
    return
  }
  let all = ATab.concat(BTab).sort((a, b) => +a - +b)
  for (const index in all) {
    cost += +all[index]
    console.log(cost);
    if (cost < time) continue;
    console.log(cost > time ? +index : +index + 1);
    return
  }


  let input = require("fs").readFileSync("/dev/stdin", "utf8").split("\n")
  let time = +input[0].split(" ")[2]
  let ATab = input[1].split(" ")
  let BTab = input[2].split(" ")
  let count = 0
  let cost = 0
  if (+time < +ATab[0] && +time < +BTab[0]) {
    console.log(count);
    return
  }
  let all = ATab.concat(BTab).sort((a, b) => +a - +b)
  for (const index in all) {
    cost += +all[index]
    if (cost < time) continue;
    console.log(cost > time ? index - 1 : index);
    return
  }


function main(arg) {
    let [N,M,K] = arg.split("\n")[0].split(" ").map(Number)
    let A = arg.split("\n")[1].split(" ").map(Number)
    let B = arg.split("\n")[2].split(" ").map(Number)

    let a = [A[0]]
    for(let i=1; i<N; i++) {
        a.push(a[i-1]+A[i])
    }
    //console.log(a)
    let b = [B[0]]
    for(let i=1; i<M; i++) {
        b.push(b[i-1]+B[i])
    }
    //console.log(b)

    let j = M-1
    let sum = 0
    for(let i=0; i<N; i++) {
        let tmpB = K - a[i]
        if(a[i] > K)break
        while(b[j] > tmpB) {
            //console.log(b[j])
            j--
        }
        sum = Math.max(i+1+j+1, sum)
        //console.log(`  tmpB=${tmpB}, i=${i}, j=${j}`)
    }
    console.log(sum)

}

main(require("fs").readFileSync("/dev/stdin", "utf8"));


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')

const K = Number(inp[0].split(" ")[2])
const timeA = inp[1].split(" ").map(e => parseInt(e, 10))
const timeB = inp[2].split(" ").map(e => parseInt(e, 10))
let timer = 0
let counter = 0
while (timer <= K){
    if (timer + timeA[0] <= K || timer + timeB[0] <= K){
        if (timeA.length === 0 && timeB.length === 0 ){
            break
        } else if (timeA[0] >= timeB[0]){
            timer += timeB[0]
            timeB.shift()
            counter ++
            continue
        } else if (timeA[0] < timeB[0]){
            timer += timeA[0]
            timeA.shift()
            counter ++
            continue
        } else if (timeA.length === 0 || timeB.length !== 0){
            timer += timeB[0]
            timeB.shift()
            counter ++
            continue
        }  else if (timeB.length === 0 || timeA.length !== 0){
            timer += timeA[0]
            timeA.shift()
            counter ++
            continue
        }
    } else {
        break
    }
}
console.log(counter)


function main(lines) {
  const [N, M, K] = splitN(lines[0]);
  const A = splitN(lines[1]);
  const B = splitN(lines[2]);

  let t = K, i = 0;
  while (t-A[i] >= 0) {
    t -= A[i];
    i++;
  }

  let res = i, j = 0;
  while (true) {
    while (t-B[j] >= 0) {
      t -= B[j];
      j++;
    }
    res = Math.max(res, i+j);
    if (!i) break;
    t += A[i];
    i--;
  }

  console.log(res);
}

main( require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n") );

function splitN(s) {
  return s.split(' ').map(Number);
}


const main = (input) => {
  input = input.trim().split('\n')
  const [N, M, K] = input[0].split(' ').map(BigInt)
  const booksA = input[1].split(' ').map(BigInt)
  const booksB = input[2].split(' ').map(BigInt)

  let currentSum = 0n
  const maxB = []
  for (let i = 0; i < booksB.length; i++) {
    currentSum += booksB[i]
    maxB.push(booksB[i])

    if (currentSum > K) {
      currentSum -= maxB.pop()
      break
    }
  }

  let ans = maxB.length

  let A_sum = 0n
  const Alist = []
  for (let i = 0; i < booksA.length; i++) {
    A_sum += booksA[i]
    Alist.push(booksA[i])

    while (A_sum + currentSum > K && maxB.length) currentSum -= maxB.pop()
    if (A_sum + currentSum > K) break

    ans = Math.max(ans, Alist.length + maxB.length)
  }

  return console.log(ans)
}

process.env.MYTEST ? test() : main(require('fs').readFileSync('/dev/stdin', 'utf8'))


inp = require('fs').readFileSync('/dev/stdin', 'utf8').trim().split('\n')

const K = Number(inp[0].split(" ")[2])
const timeA = inp[1].split(" ").map(Number)
const timeB = inp[2].split(" ").map(Number)
let timer = 0
let counter = 0
while (timer <= K){
    if (timer + timeA[0] <= K || timer + timeB[0] <= K){

        if (timeA[0] < timeB[0]){
            timer += Number(timeA[0])
            timeA.shift()
            counter ++
        } else if (timeA.length === 0 || timeB.length !== 0){
            timer += Number(timeB[0])
            timeB.shift()
            counter ++
        } else if (timeA[0] >= timeB[0]){
            timer += Number(timeB[0])
            timeB.shift()
            counter ++
        } else if (timeB.length === 0 || timeA.length !== 0){
            timer += Number(timeA[0])
            timeA.shift()
            counter ++
        } else if (timeA.length === 0 && timeB.length === 0){
            break
        }
    } else {
        break
    }
}
console.log(counter)


"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function() {return this.index < this.max},
        "next": function() { if (!this.hasNext()) {throw "ArrayIndexOutOfBoundsException";}else{return this.list[this.index++];}}
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let [N,M,K] = nextIntArray()
    K = BigInt(K)
    let a = next().split(" ").map(el => BigInt(el)).reverse()
    let b = next().split(" ").map(el => BigInt(el)).reverse()
    let pat = []
    if(a[a.length - 1] > K && b[b.length - 1] > K){
        console.log(0)
        return
    }
    const func = (past, cnt, restA, restB) => {
        // console.log(past, cnt, restA, restB)
        if(past > K ) return
        if(restA.length == 0 && restB.length == 0){
            pat.push(cnt)
            return
        }
        if(restA.length > 0 ){
            let tmp = restA.pop()
            if(past <= K && past + tmp > K){
                pat.push(cnt)
                restA.push(tmp)
            } else {
                func(past+tmp, cnt + 1, restA, restB)
                restA.push(tmp)
            }

        }
        if(restB.length>0 ){
            let tmp = restB.pop()
            if(past <= K && past + tmp > K){
                pat.push(cnt)
            } else {
                func(past+tmp, cnt + 1, restA, restB)
            }
        }
    }
    func(0n, 0, a, b)
    pat.sort((a,b) => b-a)
    console.log(pat[0])

}
Main()


"use strict"
const create = () => {
    const input = require("fs").readFileSync("/dev/stdin", "utf8").trim().split("\n");
    const res = {
        "list": input, "index": 0, "max": input.length,
        "hasNext": function () { return this.index < this.max },
        "next": function () { if (!this.hasNext()) { throw "ArrayIndexOutOfBoundsException"; } else { return this.list[this.index++]; } }
    };
    return res;
}
const o = create();
const next = () => o.next()
const nextInt = () => parseInt(o.next())
const nextStrArray = () => o.next().split(" ")
const nextIntArray = () => o.next().split(" ").map(el => parseInt(el))
const nextCharArray = () => o.next().split("")
const hasNext = () => o.hasNext()
const myout = (...x) => console.log(...x)
const Main = () => {
    let [N, M, K] = nextIntArray()
    let a = nextIntArray()
    let b = nextIntArray()

    let tmp = 0
    let sumA = [0]
    for (let i = 0; i < a.length; i++) {
        tmp += a[i]
        sumA.push(tmp)
    }
    tmp = 0
    let sumB = [0]
    for (let i = 0; i < b.length; i++) {
        tmp += b[i]
        sumB.push(tmp)
    }
    let res = 0
    for(let i = 0, j = M; i <= N; i++){
        if(sumA[i] > K) break
        while(sumA[i] + sumB[j] > K ) j--
        res = Math.max(res, i+j)
    }
    console.log(res)
}
Main()


'use strict';
let int_input_list = [];
let count = 0;

// let answer;
function main(input) {
  let state_of_books_on_the_desk = {
  	deskA:[],
    deskB:[],
  }

  const str_list = input.replace(/\r?\n/g," ").split(" ");

  for (let i = 0; i < str_list.length; i++){
    str_list[i] = parseInt(str_list[i])
    int_input_list.push(str_list[i])
  }
  // each books minutes
  let books_minutes = int_input_list.slice(3)
  let initial_num_of_books_on_the_desk = int_input_list[0] + int_input_list[1]

  state_of_books_on_the_desk.deskA = books_minutes.slice(0, int_input_list[0])
  state_of_books_on_the_desk.deskB = books_minutes.slice(int_input_list[0])

  //console.log(state_of_books_on_the_desk)
  //console.log('int_input_list: ', int_input_list)
  //console.log('books_minutes: ',books_minutes)

  let max_minutes = int_input_list[2]
  let num_of_books_read = 0
  let sum_of_minutes = 0
  //console.log(books_minutes);
  for (let z=0; z < initial_num_of_books_on_the_desk; z++ ){
    //console.log('current state: ', state_of_books_on_the_desk)
    if (sum_of_minutes <= max_minutes){
    //console.log('state_of_books_on_the_desk.deskA[z]:',state_of_books_on_the_desk.deskA[z] )

    let current_book = Math.min(state_of_books_on_the_desk.deskA[0], state_of_books_on_the_desk.deskB[0]);
    //console.log('current_book: ',current_book)
    sum_of_minutes = sum_of_minutes + current_book
   //console.log('sum_of_minutes: ', sum_of_minutes)

    // remove element from state
    if (state_of_books_on_the_desk.deskA[z] <= state_of_books_on_the_desk.deskB[z]){
    state_of_books_on_the_desk.deskA.splice(0, 1)
    }else{
      state_of_books_on_the_desk.deskB.splice(0, 1)
    }
    }

    //sum_of_minutes = sum_of_minutes + books_minutes[z];
	//console.log(z)
    num_of_books_read = z+1
	//console.log(z)

  }
  console.log(num_of_books_read)
  };

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


function Main(input) {
    input = input.split("\n");
    const array = input[0].split(' ');
    const n = Number(array[0]);
    const m = Number(array[1]);
    const k = Number(array[2]);

    const array1 = input[1].split(' ').map( str => parseInt(str, 10) );
    const array2 = input[2].split(' ').map( str => parseInt(str, 10) );

    let num = 0;
    let time = 0;

    for (let i = 0, count = m + n; i < count; i++) {

       if (array1.length < 1) {
            time += array2[0];
            array2.shift();
        } else if (array2.length < 1) {
            time += array1[0];
            array1.shift();
        } else if (array1[0] <= array2[0]) {
            time += array1[0];
            array1.shift();
        } else {
            time += array2[0];
            array2.shift();
        }

if (time > k) {
            break;
        } else {
num ++;
}

    }

    console.log(num);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


"use strict"
function main(arg) {
    let [N,M,K] = arg.trim().split("\n")[0].split(" ").map(Number)
    let A = arg.trim().split("\n")[1].split(" ").map(Number)
    let B = arg.trim().split("\n")[2].split(" ").map(Number)
    N = A.length
    M = B.length
    K = BigInt(K)
    let ans = 0
    let sum = 0
    let a = 0
    let b = 0
    let aSum = BigInt(0)
    let bSumList = []
    let bSum = BigInt(0)
    for (b = 0; b < M; b++) {
        bSum += BigInt(B[b])
        if (bSum > K) {
            break
        }
        bSumList.push(bSum)
    }
    for (a = 0; a < N; a++) {
        aSum += BigInt(A[a])
        if (aSum > K) {
            break
        }
        // console.log(aSum)
        // let bSum = BigInt(0)
        for (b = 0; b < bSumList.length; b++) {
            bSum = bSumList[b]
            if (aSum + bSum > K) {
                break
            }
            ans = Math.max(ans, (a+1) + (b+1))
            // console.log([ans,a+1,b+1])
        }
    }
    console.log(ans)
    // console.log(sum)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict"
function main(arg) {
    let [N,M,K] = arg.trim().split("\n")[0].split(" ").map(Number)
    let A = arg.trim().split("\n")[1].split(" ").map(Number)
    let B = arg.trim().split("\n")[2].split(" ").map(Number)
    N = A.length
    M = B.length
    K = BigInt(K)
    let ans = 0
    let sum = 0
    let a = 0
    let b = 0
    let aSum = BigInt(0)
    let bSumList = new Array(B.length).fill(0)
    let bSum = BigInt(0)
    for (b = 0; b < M; b++) {
        bSum += BigInt(B[b])
        bSumList[b] = bSum
    }
    for (a = 0; a < N; a++) {
        aSum += BigInt(A[a])
        // console.log(aSum)
        // let bSum = BigInt(0)
        for (b = 0; b < M; b++) {
            bSum = bSumList[b]
            if (aSum + bSum > K) {
                break
            }
            ans = Math.max(ans, (a+1) + (b+1))
            // console.log([ans,a+1,b+1])
        }
    }
    console.log(ans)
    // console.log(sum)
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


"use strict";

function main(input) {
  input = input.trim().split("\n");
  const line_one_arr = input[0].split(" ");
  const A = input[1].split(" ");
  const B = input[2].split(" ");
  let K = BigInt(line_one_arr[2]);

  let a = parseInt(A.length); // A counter
  let b = parseInt(B.length); // B counter
  let ab = a + b;

  let n = 0;
  let m = 0;
  while (true) {
    try {
      A[n] = BigInt(A[n]);
    } catch {
      A[n] = BigInt(0);
    }
    try {
      B[m] = BigInt(B[m]) || 0;
    } catch {
      B[m] = BigInt(0);
    }
    if (a == 0 && b == 0) break;

    if (A[n] > B[m] || a == 0) {
      if (K - B[m] < 0) break;
      K = K - B[m];
      b--;
      m++;
    } else {
      if (K - A[n] < 0) break;
      K = K - A[n];
      a--;
      n++;
    }
  }
  const ans = ab - (a + b);

  console.log(ans);
}

function numberSort(array) {
  array.sort(f);
  return array;
}

var f = function (a, b) {
  return a - b;
};

main(require("fs").readFileSync("/dev/stdin", "utf-8"));


function main(arg) {
  const array = arg.trim().split("\n");
  const firstArray = array[0].trim().split(" ");
  let N = parseInt(firstArray[0], 10);
  let M = parseInt(firstArray[1], 10);
  let K = parseInt(firstArray[2], 10);
  let aBooks = array[1].trim().split(" ");
  let bBooks = array[2].trim().split(" ");

  let result = 0;
  let counter = 0;

  // TODO 処理を書く
  while (counter < N + M) {
    counter++;
    let A = 0;
    let B = 0;
    let readBook = 0;

    if (aBooks.length == 0 && bBooks.length == 0) {
      break;
    }

    A = parseInt(aBooks[0], 10);
    B = parseInt(bBooks[0], 10);

    if (A < B) {
      readBook = A;
      aBooks.shift();
    } else {
      readBook = B;
      bBooks.shift();
    }

    K -= readBook;
    if (K < 0) {
      break;
    }
    result++;
  }

  console.log(result);
}
main(require("fs").readFileSync("/dev/stdin", "utf8"));
// main(
//   "5 4 1\n1000000000 1000000000 1000000000 1000000000 1000000000\n1000000000 1000000000 1000000000 1000000000"
// );
// main("1 1 240\n1\n1");
// main("3 4 730\n60 90 120\n80 150 80 150");
// main("3 4 240\n60 90 120\n80 150 80 150");
//https://atcoder.jp/contests/abc167/tasks/abc167_b


'use strict';
let int_input_list = [];
let count = 0;

// let answer;
function main(input) {
  const str_list = input.replace(/\r?\n/g," ").split(" ");

  for (let i = 0; i < str_list.length; i++){
    str_list[i] = parseInt(str_list[i])
    int_input_list.push(str_list[i])
  }

  let books_minutes = []
  books_minutes = int_input_list.slice(3)

  let num_of_books_on_the_desk = int_input_list[0]+int_input_list[1]

  //console.log('int_input_list: ', int_input_list)
  //console.log('books_minutes: ',books_minutes)

  let max_minutes = int_input_list[2]

  // sort each books' minutes
  books_minutes.sort(function(a, b) {
  return a - b;
});

  let num_of_books_read = 0
  let sum_of_minutes = 0
  //console.log(books_minutes);
  for (let z=0; z < num_of_books_on_the_desk; z++ ){

    sum_of_minutes = sum_of_minutes + books_minutes[z];
	//console.log(z)
    num_of_books_read = z
	//console.log(z)

  }
  console.log(num_of_books_read)
  };

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


"use strict";

function main(input) {
  input = input.trim().split("\n");
  const line_one_arr = input[0].split(" ");
  const A = input[1].split(" ");
  const B = input[2].split(" ");
  let K = BigInt(line_one_arr[2]);

  let a = parseInt(A.length); // A counter
  let b = parseInt(B.length); // B counter
  let ab = a + b;

  let n = 0;
  let m = 0;
  while (true) {
    A[n] = BigInt(A[n]);
    B[m] = BigInt(B[m]);
    if (a == 0 && b == 0) break;

    if (A[n] > B[m] || a == 0) {
      if (K - B[m] < 0) break;
      K = K - B[m];
      b--;
      m++;
    } else {
      if (K - A[n] < 0) break;
      K = K - A[n];
      a--;
      n++;
    }
  }
  const ans = ab - (a + b);

  console.log(ans);
}

function numberSort(array) {
  array.sort(f);
  return array;
}

var f = function (a, b) {
  return a - b;
};

main(require("fs").readFileSync("/dev/stdin", "utf-8"));


process.stdin.resume();
process.stdin.setEncoding("utf8");
process.stdin.on("data", input => {
  const splitted = input.split("\n");
  const nums = splitted[0].split(" ");
  const N = Number(nums[0]);
  const M = Number(nums[1]);
  const K = Number(nums[2]);
  const Ak = createReadTime(splitted[1]);
  const Bk = splitted[2].split(" ");
  let n = N;
  let readCount = n;

  let currentReadTime = Ak[N].total;
  let a = Ak[n];
  for (const b of Bk) {
    const num = Number(b);
    if (currentReadTime + num <= K) {
      readCount++;
      currentReadTime += num;
      continue;
    }

    if (a.val >= num) {
      // 入れ替え
      n--;
      currentReadTime+= num- a.val;
      a = Ak[n];
      continue;
    }
    break;
  }
  console.log(readCount);
});

const createReadTime = (array, K) => {
  let prevTotal = 0;
  return array.split(" ").reduce((total, val, index) => {
    if (prevTotal >= K) {
      return total;
    }
    const num = Number(val);
    prevTotal += num;
    if (prevTotal > K) {
      return total;
    }
    total[index + 1] = { val: num, total: prevTotal };
    return total;
  }, {});
};


function main(input){
  input = input.split('\n');
  const [n, m, k] = input[0].split(' ').map(x=>Number(x));
  const a = input[1].split(' ').map(x=>Number(x)).reverse();
  const b = input[2].split(' ').map(x=>Number(x)).reverse();

  let count = 0;
  let totalTime = 0;
  while(totalTime <= k){

    count++;
    if( (a.length === 0) && (b.length === 0)) {break;}

    let next;
    if(a.length === 0){
      next = b.pop();
    }else if(b.length === 0){
      next = a.pop();
    }else if(a[a.length-1] <= b[b.length-1]){
      next = a.pop();
    }else{
      next = b.pop();
    }
    totalTime += next;
  }

  console.log(count-1);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const input = require("fs").readFileSync("/dev/stdin", "utf8")

;(input => {

    const lines = input.split('\n')
    const [N, M, K] = lines[0].split(' ').map(BigInt)
    const A = lines[1].split(' ').map(BigInt)
    const B = lines[2].split(' ').map(BigInt)

    let t = 0n
    const max = A.length + B.length
    let a = 0
    let b = 0
    for (var i = 0; i < max; i++) {
        if (!B[b] || A[a] < B[b]) {
            t += A[a]
            a++
        } else {
            t += B[b]
            b++
        }
        if (t > K) {
            break
        }
    }

    console.log(i)

})(input)


function main(input){
  const [l1, l2, l3] = input.split('\n');
  let [N, M, K] = l1.split(' ');
  K = Number(K);
  let aArray = l2.split(' ');
  let bArray = l3.split(' ');
  const aArrayLenOri = aArray.length;
  const bArrayLenOri = bArray.length;
  while(K > 0 && (aArray.length > 1 || bArray.length > 1)) {
    let aTime = (aArray.length === 0) ? 0 : aArray[0];
    let bTime = (bArray.length === 0) ? 0 : bArray[0];
    console.log(K,aTime,bTime);
    if (aTime === 0 && bTime === 0) K = 0;
    if (aTime < bTime && K >= aTime) {
      K - aTime;
      aArray.shift();
      return;
    } else if(bTime < aTime && K >= bTime) {
      K - bTime;
      bArray.shift();
      return;
    }
  }
  console.log((aArrayLenOri - aArray.length) + (bArrayLenOri - bArray.length));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


let main = (input) => {
    let usrInput = input.split(/\n/)
    let sample = usrInput[0].split(/\s+/).map(Number)
    let bookA = usrInput[1].split(/\s+/).map(Number)
    let bookB = usrInput[2].split(/\s+/).map(Number)

    let book = 0
    for (let time = 0; time < sample[2];) {
        if (bookA.length !== 0 && bookB.length !== 0) {
            if (bookA[0] < bookB[0]) {
                time += bookA.shift()
                book++
            } else {
                time += bookB.shift()
                console.log(bookA)
                book++
            }
        }
        if (bookA.length === 0 && bookB.length !== 0) {
            if (time + bookB[0] <= sample[2]) {
                time += bookB.shift()
                book++
            }
        }
        if (bookB.length === 0 && bookA.length !== 0) {
            if (time + bookA[0] <= sample[2]) {
                time += bookA.shift()
                book++
            }
        }

        if (bookB.length === 0 && bookA.length === 0)
            break
    }

    console.log(book)
}

main(require('fs').readFileSync('/dev/stdin', 'utf8'))


const Main = input => {
    input = input.split("\n");
    const nmk = input[0].split(" ").map(value => parseInt(value, 10));
    const n = nmk[0];
    const m = nmk[1];
    const k = nmk[2];
    const a = input[1].split(" ").map(value => parseInt(value, 10));
    const b = input[2].split(" ").map(value => parseInt(value, 10));

    let time = 0;
    let count = 0;

    // 与えられた配列の0番目の本を読む
    const read = arr => {
        // aの一番上の本を読む
        time += arr[0];

        //読んだら取り除く
        arr.shift();

        // 読んだ本の数を増やす
        count++;
    }

    for(let i = 0; i < n + m; i++) {
        // どちらの本も読み切っている場合
        if(a.length === 0 && b.length === 0) break;

        // Aの本がない場合
        if(a.length === 0) {
            // Bの本を読んでk分を超えるなら詰みなので脱出
            if(time + b[0] > k) break;
            read(b);
        }
        // Bの本がない場合
        else if(b.length === 0) {
            // Aの本を読んでk分を超えるなら詰みなので脱出
            if(time + a[0] > k) break;
            read(a);
        }
        // まだどちらの本もある場合
        else {
            // どちらの本を読んでもk分を超えるなら詰みなので脱出
            if(time + a[0] > k && time + b[0] > k) break;

            if(a[0] <= b[0]) {
                // aの一番上の本を読む
                read(a);
            } else {
                // bの一番上の本を読む
                read(b);
            }
        }
    }

    console.log(count);
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));


function main(input){
  const [l1, l2, l3] = input.split('\n');
  let [N, M, K] = l1.split(' ');
  let aArray = l2.split(' ');
  let bArray = l3.split(' ');
  const aArrayLenOri = aArray.length;
  const bArrayLenOri = bArray.length;
  while(K > 0 && (aArray.length > 1 || bArray.length > 1)) {
    const aTime = (aArray.length === 0) ? 0 : aArray[0];
    const bTime = (bArray.length === 0) ? 0 : bArray[0];
    if (aTime < bTime && K >= aTime) {
      if (K >= aTime)
      K - aTime;
      aArray.shift();
    } else if(bTime < aTime && K >= aTime) {
      K - bTime;
      bArray.shift();
    }
  }
  console.log((aArrayLenOri - aArray.length) + (bArrayLenOri - bArray.length));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


console.log((args=>{
  const [[N,M,K],A,B] = args.trim().split('\n').map( r=>r.split(' ').map(v=>v|0) );
  let max = 0, sA = 0;
  for ( let i = 0; i <= N; i++ ) {
    if ( sA > K ) break;
    let sB = 0;
    for ( let j = 0; j <= M; j++ ) {
      if ( sA + sB > K ) break;
      else if ( i+j > max ) max = i+j;
      sB += B[j];
    }
    sA += A[i];
  }
  return `${max}`;
})(require('fs').readFileSync('/dev/stdin', 'utf8')));


function main(input){
  const [l1, l2, l3] = input.split('\n');
  let [N, M, K] = l1.split(' ');
  let aArray = l2.split(' ');
  let bArray = l3.split(' ');
  const aArrayLenOri = aArray.length;
  const bArrayLenOri = bArray.length;
  while(K > 0 && (aArray.length > 1 || bArray.length > 1)) {
    const aTime = (aArray.length === 0) ? 0 : aArray[N - 1];
    const bTime = (bArray.length === 0) ? 0 : bArray[M - 1];
    if (aTime < bTime) {
      K - aTime;
      aArray.pop();
    } else {
      K - bTime;
      bArray.pop();
    }
  }
  console.log((aArrayLenOri - aArray.length) + (bArrayLenOri - bArray.length));
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


// inputに入力データ全体が入る
function Main(input) {
	var ans = 0
	// 1行目がinput[0], 2行目がinput[1], …に入る
	input = input.trim().split("\n")
	// var arr = input.trim().split("\n")
	var max = input[0].split(' ').map(n => parseInt(n))[2]
	var da = input[1].split(' ').map(n => parseInt(n))
	var db = input[2].split(' ').map(n => parseInt(n))
	var now = 0
	var ai = 0
	var bi = 0

	while (now < max) {
		var read
		var isa
		if (da[ai] == -1 && db[bi] == -1) {
			break
		} else if (da[ai] == -1 && db[bi] > 0) {
			read = db[bi]
			isa = false
		} else if (da[ai] == -1 && db[bi] > 0) {
			read = da[ai]
			isa = true
		} else if (da[ai] < db[bi]) {
			read = da[ai]
			isa = true
		} else {
			read = db[bi]
			isa = false
		}

		if (now + read <= max) {
			now = now + read
			ans++
		} else {
			break
		}

		if (isa) {
			ai++
			if (da[ai] == undefined) da[ai] = -1
		} else {
			bi++
			if (db[bi] == undefined) db[bi] = -1
		}
	}

	//出力
	console.log(ans)
}
//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
// Main(require('fs').readFileSync('./input.txt', 'utf-8'));