// "static void main" must be defined in a public class.
import java.util.* ;
public class Main {
    public static void main(String[] args) {
        Scanner S = new Scanner( System.in ) ;
        Main obj = new Main() ;
        int t = S.nextInt() ;
        int min = Integer.MAX_VALUE ;
        if( t<1000 ) {

             min = t  ;
        }
        int change = t%1000 ;
        System.out.println( Math.min( min , (1000-change) ) ) ;
    }
}
// "static void main" must be defined in a public class.
// import java.util.* ;
// public class Main {
//     public static void main(String[] args) {
//         Scanner S = new Scanner( System.in ) ;
//         Main obj = new Main() ;
//         int t = S.nextInt() ;

//     }
// }


import java.util.*;
import java.lang.*;
import java.io.*;
public class Main {

	public static void main(String[] args)throws java.lang.Exception
    {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int n =Integer.parseInt(br.readLine());
		System.out.println(n%1000==0?0:1000-n%1000);
	}

}

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

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.

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.


import java.util.*;
class Main {

    static Scanner scan = new Scanner(System.in);
    public static void main(String[] args) {
            int N = scan.nextInt();
            int change  = Integer.MIN_VALUE;
           if(N % 1000 == 0) {
               change = 0;
           } else {
                int rem = N / 1000;
                change = (rem + 1) * 1000 - N;
            }
            System.out.println(change);
    }
}


import java.util.*;
public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        int change = 1000-(n%1000);
        if(change == 1000) change = 0;
        System.out.println(change);

    }
}


import java.util.*;
    public class Main{
        public static void main(String[] args) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            int a = n%1000;
            System.out.println(a);
        }
    }


import java.util.*;

public class Main { //クラス名はMain
    public static void main(String[] args) {
      //整数の入力
      Scanner sc = new Scanner(System.in);
      int A = Integer.parseInt(sc.next());

      int oturi = A%1000 == 0 ? A/1000 : A/1000 + 1;

      System.out.println(oturi);
    }
}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		StringBuilder ans = new StringBuilder();
		while (--t >= 0) {
			int n = sc.nextInt();
			int numOfNotes = n / 1000;
			if (n % 1000 != 0)
				numOfNotes++;
			System.out.println(1000 * numOfNotes - n);
		}
	}
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println(1000 - sc.nextInt() % 1000);
    }
}


import java.util.*;

public class Main {
    public static void main(String args[]) {
        Scanner scn = new Scanner(System.in);
        int n = scn.nextInt();
        int pay = 1000;

        while(n>pay){
            pay += 1000;
        }

        System.out.println(pay-n);

        scn.close();

    }

}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
	// write your code here

        Scanner src = new Scanner(System.in);

        int n = src.nextInt();

        System.out.println(n%1000);

    }
}


//Created by Aminul on 7/5/2020.

import java.io.*;
import java.util.*;

import static java.lang.Math.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Scanner in = new Scanner(System.in);
        PrintWriter pw = new PrintWriter(System.out);
        int n = in.nextInt();
        int res = n / 1000;
        if (n % 1000 != 0) res++;
        res = (res * 1000) - n;
        pw.println(res);

        pw.close();
    }

    static void debug(Object... obj) {
        System.err.println(Arrays.deepToString(obj));
    }
}


import java.io.*;
import java.util.*;

/**
 * Created by Ayushi on 05 Jul 2020.
 * Problem:
 * Round:
 */

public class Main {
    public static void main(String[] args) throws IOException {
        StringTokenizer st;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        st = new StringTokenizer(br.readLine(), " ");
        int n = Integer.parseInt(st.nextToken());
        br.close();
        int ans = 1000 - (n % 1000);
        System.out.println(ans);
    }
}


import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();

        System.out.println(n % 1000);
    }
}


import java.awt.Point;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Locale;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class Main implements Runnable{

	private static final int LIMIT = 1800; // ループで回せる時間
	private static void solve(FastIO io) {
		/*
		 * author: 31536000
		 * Introduction to Heuristics Contest A問題
		 * 考察メモ
		 * まず、各日に決められるコンテストは高々1つなので、それを焼きなましすることを考える
		 * ここで、ある日に開くコンテストを変えた場合に変わる情報は次に開催するlastだけ
		 * 従って、更新はO(1)で行えるはず
		 *
		 * 実際に更新をO(1)で行う方法を考える
		 * データ構造として、双方向連結リストを考える
		 * 各日のコンテストは、直前と直後に開催されたコンテストを記録する
		 * この時、ある日のコンテストの種類を変更することは次のように表される
		 * 1. そのコンテストのスコアを減らす
		 * 2. そのコンテストの次に開かれた同じコンテストの直前コンテストを更新し、スコアを更新する(減らす)
		 * 3. コンテストを変更し、スコアを増やす
		 * 4. 直前と直後を繋ぐ…えー、O(D)やん、もっと速くならない？
		 *
		 * 次の情報: d日目以前に開かれたi番目のコンテストのうち、一番最後の物を求める
		 * これは、計算量O(logN) (TreeSet)以外にできるか？
		 * 区間max/一点更新で解けそうじゃない？
		 * つまり、一点更新で開かれたコンテストのポインタを入れれば、区間maxが最後のもの
		 * nullは最小、両方が非nullなら右側優先でおっけー
		 */
		io.setAutoFlush(true);
		Marathon marathon = new Marathon(io);
		MarathonTimer timer = new MarathonTimer(marathon);
		timer.start(LIMIT);
	}

	private static class Marathon implements MarathonInterface {
		private FastIO io;
		private Random rnd;
		private int loop;

		private static final int CONTEST = 26;
		private final int D;
		private final int HALF_OF_D;
		private final int[] c;
		private final int[][] s;
		private final int[] s2; // sを展開したもの、少し速くなると嬉しい……

		private final Contest[] contest; // D日目に開かれたコンテスト
		// private final SegmentTree[] segment; // 各コンテストを高速検索するためのRMQ

		private final Contest[] begin, end; // 各コンテストの連結リストの端

		int score;

		class Contest {
			Contest last, next;
			int day, type;
			Contest(int day, int type) {
				this.type = type;
				this.day = day;
				last = next = this;
			}
			@Override
			public String toString() {
				return "Contest " + type + " is held " + day;
			}
		}

		/*private class SegmentTree {
			private Contest[] tree;
			private final int size;
			private final Contest MIN, MAX;
			public SegmentTree(int type) {
				size = Integer.highestOneBit(D + 1) << 1;
				tree = new Contest[size * 2];
				tree[size] = MIN = new Contest(-1, type);
				tree[tree.length - 1] = MAX = new Contest(D, type);
			}
			public final void set(int index, final Contest contest) {
				index += size + 1;
				tree[index] = contest;
				while(index != 0) {
					index >>= 1;
					Contest right = tree[index << 1 | 1];
					tree[index] = right == null ? tree[index << 1] : right;
				}
			}
			public final Contest get() {
				return MAX;
			}
			public final Contest get(int toIndex) {
				int fromIndex = size;
				toIndex += size;
				while(fromIndex <= toIndex) {
					if ((toIndex & 1) == 0) {
						Contest right = tree[toIndex];
						if (right != null) return right;
						-- toIndex;
					}
					fromIndex >>= 1;
					toIndex >>= 1;
				}
				return MIN;
			}
		}*/

		public Marathon(FastIO io) {
			this.io = io;
			rnd = new Random();
			D = io.nextInt();
			HALF_OF_D = D >> 1;
			c = io.nextInt(CONTEST);
			s = io.nextInt(CONTEST, D);
			s2 = new int[CONTEST * D];
			for (int i = 0;i < D;++ i) {
				for (int j = 0;j < CONTEST;++ j) s2[i * CONTEST + j] = s[i][j];
			}
			contest = new Contest[D];
			//segment = new SegmentTree[CONTEST];
			//for (int i = 0;i < CONTEST;++ i) segment[i] = new SegmentTree(i);
			begin = new Contest[CONTEST];
			end = new Contest[CONTEST];
			for (int i = 0;i < CONTEST;++ i) {
				begin[i] = new Contest(-1, i);
				end[i] = new Contest(D, i);
			}
		}

		private int want(final int contest, final int wait) {
			return c[contest] * wait * (wait - 1) >> 1;
		}

		@Override
		public void read() {
		}

		@Override
		public void init() {
			loop = 0;

			// 貪欲法で構築しておく
			Contest[] last = Arrays.copyOf(begin, CONTEST); // 最後に開かれたタイミング
			for (int i = 0;i < D;++ i) {
				int max = 0, maxScore = -1;
				for (int j = 0;j < CONTEST;++ j) {
					int score = s2[i * CONTEST + j] + c[j] * (i - last[j].day);
					if (maxScore < score) {
						maxScore = score;
						max = j;
					}
				}
				contest[i] = new Contest(i, max);
				contest[i].last = last[max];
				contest[i].last.next = contest[i];
				last[max] = contest[i];
				score += s2[i * CONTEST + max];
				score -= want(max, i - contest[i].last.day);
			}
			for (int i = 0;i < CONTEST;++ i) {
				Contest tmp = end[i];
				tmp.last = last[i];
				tmp.last.next = tmp;
				score -= want(i, D - tmp.last.day);
			}
			seed = rnd.nextInt();
			for (int i = 0;i < log.length;++ i) log[i] = Math.log(nextDouble());
		}

		private int seed;
		private static final int XOR_MASK = 0x7FFFFFFF;
		private static final int LOG_SIZE = 1 << 10;
		private static final int LOG_MASK = LOG_SIZE - 1;
		final double[] log = new double[LOG_SIZE];
		int xorshift() {
			seed = seed ^ (seed << 13);
			seed = seed ^ (seed >>> 17);
			return seed = seed ^ (seed << 5);
		}

		public int nextInt(int bound) {
			return (xorshift() & XOR_MASK) % bound;
		}

		/*public final int nextInt(int bound) {
			int bits, val;
			do {
				bits = xorshift() & XOR_MASK;
				val = bits % bound;
			} while (bits - val + (bound - 1) < 0);
			return val;
		}*/

		private static final double RND_DOUBLE_INV = 1.0 / (1L << 53);
		public final double nextDouble() {
			return (((xorshift() & 0x03FFFFFFL) << 27) + (xorshift() & 0x07FFFFFF)) * RND_DOUBLE_INV;
		}

		private static final int NEARLY_INV_LIMIT = 32 - Integer.numberOfLeadingZeros(LIMIT - 1);
		@Override
		public final void update(int delay) { // TODO UPDATE
			++ loop;

			int patturn = nextInt(101 - (delay * 90 >> NEARLY_INV_LIMIT));
			if (patturn < 9) { // パターン1: 特定の日付のコンテストの種類を変える
				int day = nextInt(D);
				int swap = nextInt(CONTEST - 1);
				Contest now = contest[day];
				int type = now.type;
				if (swap >= now.type) ++ swap;

				int change = 0; // 更新されるスコアの増え幅
				change += want(type, day - now.last.day); // 元々の値
				change += want(type, now.next.day - day); // 元々の値
				change -= want(type, now.next.day - now.last.day);
				change -= s2[day * CONTEST + type];
				Contest swapNext;
				if (day <= HALF_OF_D) {
					swapNext = begin[swap];
					while(swapNext.day < day) swapNext = swapNext.next;
				} else {
					swapNext = end[swap];
					while(swapNext.last.day > day) swapNext = swapNext.last;
				}
				change += want(swap, swapNext.day - swapNext.last.day); // 元々の値
				change -= want(swap, swapNext.day - day);
				change -= want(swap, day - swapNext.last.day);
				change += s2[day * CONTEST + swap];
				if (isChange(change, delay)) {
					score += change;
					now.type = swap;
					now.next.last = now.last;
					now.last.next = now.next;
					swapNext.last.next = now;
					now.last = swapNext.last;
					swapNext.last = now;
					now.next = swapNext;
				}
			 /* } else if (patturn < 20){ // パターン2: 二つのコンテストの日付を入れ替える
				int day1 = nextInt(D);
				int day2 = nextInt(D - 1);
				if (day2 >= day1) ++ day2;
				Contest d1 = contest[day1];
				Contest d2 = contest[day2];
				int type1 = d1.type, type2 = d2.type;
				SegmentTree segment1 = segment[type1], segment2 = segment[type2];
				if (d1.type == d2.type) {
					-- loop;
					return; // swapするだけ無駄
				}
				Contest day1Last = d1.last.day < day2 && day2 < d1.next.day ? null : segment1.get(day2);
				Contest day2Last =  d2.last.day < day1 && day1 < d2.next.day ? null : segment2.get(day1);
				int change = 0; // 更新されるスコアの増え幅
				change -= s2[day1 * CONTEST + type1];
				change += s2[day2 * CONTEST + type1];
				change += want(type1, d1.next.day - day1);
				change += want(type1, day1 - d1.last.day);
				if (day1Last == null) {
					change -= want(type1, d1.next.day - day2);
					change -= want(type1, day2 - d1.last.day);
				} else {
					change -= want(type1, d1.next.day - d1.last.day);
					change += want(type1, day1Last.next.day - day1Last.day);
					change -= want(type1, day1Last.next.day - day2);
					change -= want(type1, day2 - day1Last.day);
				}
				change -= s2[day2 * CONTEST + type2];
				change += s2[day1 * CONTEST + type2];
				change += want(type2, d2.next.day - day2);
				change += want(type2, day2 - d2.last.day);
				if (day2Last == null) {
					change -= want(type2, d2.next.day - day1);
					change -= want(type2, day1 - d2.last.day);
				} else {
					change -= want(type2, d2.next.day - d2.last.day);
					change += want(type2, day2Last.next.day - day2Last.day);
					change -= want(type2, day2Last.next.day - day1);
					change -= want(type2, day1 - day2Last.day);
				}
				if (isChange(change, delay)) {
					score += change;
					segment1.set(day1, null);
					segment1.set(day2, d1);
					segment2.set(day2, null);
					segment2.set(day1, d2);
					contest[day2] = d1;
					contest[day1] = d2;
					d1.day = day2;
					d2.day = day1;
					if (day1Last != null) {
						d1.last.next = d1.next;
						d1.next.last = d1.last;
						d1.next = day1Last.next;
						d1.last = day1Last;
						day1Last.next.last = d1;
						day1Last.next = d1;
					}
					if (day2Last != null) {
						d2.last.next = d2.next;
						d2.next.last = d2.last;
						d2.next = day2Last.next;
						d2.last = day2Last;
						day2Last.next.last = d2;
						day2Last.next = d2;
					}
				} // */
			} else { // パターン3: 近いコンテストを入れ替える
				int day1 = nextInt(D - 13);
				int day2 = nextInt(13) + 1 + day1;
				Contest d1 = contest[day1];
				Contest d2 = contest[day2];
				int type1 = d1.type, type2 = d2.type;
				if (type1 == type2) {
					-- loop;
					return;
				}
				Contest day1Last, day2Last;
				if (d1.last.day < day2 && day2 < d1.next.day) {
					day1Last = null;
				} else {
					day1Last = d1;
					while(day1Last.next.day < day2) day1Last = day1Last.next;
				}
				if (d2.last.day < day1 && day1 < d2.next.day ) {
					day2Last = null;
				} else {
					day2Last = d2;
					while(day2Last.last.day >= day1) day2Last = day2Last.last;
					day2Last = day2Last.last;
				}
				int change = 0; // 更新されるスコアの増え幅
				change -= s2[day1 * CONTEST + type1];
				change += s2[day2 * CONTEST + type1];
				change += want(type1, d1.next.day - day1);
				change += want(type1, day1 - d1.last.day);
				if (day1Last == null) {
					change -= want(type1, d1.next.day - day2);
					change -= want(type1, day2 - d1.last.day);
				} else {
					change -= want(type1, d1.next.day - d1.last.day);
					change += want(type1, day1Last.next.day - day1Last.day);
					change -= want(type1, day1Last.next.day - day2);
					change -= want(type1, day2 - day1Last.day);
				}
				change -= s2[day2 * CONTEST + type2];
				change += s2[day1 * CONTEST + type2];
				change += want(type2, d2.next.day - day2);
				change += want(type2, day2 - d2.last.day);
				if (day2Last == null) {
					change -= want(type2, d2.next.day - day1);
					change -= want(type2, day1 - d2.last.day);
				} else {
					change -= want(type2, d2.next.day - d2.last.day);
					change += want(type2, day2Last.next.day - day2Last.day);
					change -= want(type2, day2Last.next.day - day1);
					change -= want(type2, day1 - day2Last.day);
				}
				if (isChange(change, delay)) {
					score += change;
					//SegmentTree segment1 = segment[type1], segment2 = segment[type2];
					//segment1.set(day1, null);
					//segment1.set(day2, d1);
					//segment2.set(day2, null);
					//segment2.set(day1, d2);
					contest[day2] = d1;
					contest[day1] = d2;
					d1.day = day2;
					d2.day = day1;
					if (day1Last != null) {
						d1.last.next = d1.next;
						d1.next.last = d1.last;
						d1.next = day1Last.next;
						d1.last = day1Last;
						day1Last.next.last = d1;
						day1Last.next = d1;
					}
					if (day2Last != null) {
						d2.last.next = d2.next;
						d2.next.last = d2.last;
						d2.next = day2Last.next;
						d2.last = day2Last;
						day2Last.next.last = d2;
						day2Last.next = d2;
					}
				}
			}
		}

		private static final int START_TEMP = 1500; // TODO 焼きなまし関数
		private static final int END_TEMP = 150;
		private static final int DIFF = START_TEMP - END_TEMP;
		private static final double INV_LIMIT = 1.0 / LIMIT;

		private boolean isChange(int change, int delay) {
//			return change >= 0; // 山登り法
			double tmp = temperature(delay);
			// return nextDouble() <= Math.exp(change / tmp);
			return change >= tmp * log[xorshift() & LOG_MASK];
		}

		private static double temperature(int delay) {
			return DIFF * delay * INV_LIMIT + END_TEMP;
		}

		@Override
		public void finish() {
			io.debugln("loop:" + loop + ", score:" + Math.max(1000000 + score, 0));
			for (int i = 0;i < D;++ i) {
				io.println(contest[i].type + 1);
			}
		}

	}

	/** デバッグ用コードのお供に */
	private static boolean DEBUG = false;
	/** 確保するメモリの大きさ(単位: MB)*/
	private static final long MEMORY = 64;
	private final FastIO io;

	public static void main(String[] args) {
	        Thread.setDefaultUncaughtExceptionHandler((t, e) -> e.printStackTrace());
	        new Thread(null, new Main(), "", MEMORY * 1048576).start();
	}

	public Main() {
		this(new FastIO());
	}

	public Main(FastIO io) {
		this.io = io;
		if (DEBUG) {
			io.setAutoFlush(true);
			io.debugln("debug mode");
		}
	}

	@Override
	public void run() {
		solve(io);
		io.flush();
	}

	// 以下、ライブラリ

	private static interface MarathonInterface {
		/**
		 * 標準入力を受け取る関数です。
		 */
		public void read();
		/**
		 * 受け取った標準入力から、処理しやすいように加工する関数です。
		 */
		public void init();
		/**
		 * 近傍を探したりなど、毎回更新の処理を行う関数です。
		 * @param delay 残り時間
		 */
		public void update(int delay);
		/**
		 * 求まった結果を出力する関数です。
		 */
		public void finish();
	}

	private static class MarathonTimer implements Runnable {

		private MarathonInterface marathon;
		private volatile boolean roopFlag;
		private ScheduledExecutorService  threadPool;
		private ScheduledFuture<?> future;

		public MarathonTimer(Marathon marathon) {
			this.marathon = marathon;
			threadPool = Executors.newScheduledThreadPool(2);
			marathon.read();
		}

		public void start(int millis) {
			marathon.init();
			roopFlag = true;
			future = threadPool.schedule(() -> roopFlag = false, millis, TimeUnit.MILLISECONDS);
			threadPool.execute(this);
			try {
				threadPool.awaitTermination(7, TimeUnit.DAYS);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void run() {
			while(roopFlag) {
				int delay = (int)future.getDelay(TimeUnit.MILLISECONDS);
				for (int i = 0;i < 16384;++ i) marathon.update(delay); // TODO 定数ループ増やしすぎるとTLEするので、上手くループ数見て調整して
			}
			marathon.finish();
			threadPool.shutdown();
		}
	}

	/**
	 * 高速な入出力を提供します。
	 * @author 31536000
	 *
	 */
	public static class FastIO {
		private InputStream in;
		private final byte[] buffer = new byte[1024];
		private int read = 0;
		private int length = 0;
		private PrintWriter out;
		private PrintWriter err;
		private boolean autoFlush = false;

		public FastIO() {
			this(System.in, System.out, System.err);
		}

		public FastIO(InputStream in, PrintStream out, PrintStream err) {
			this.in = in;
			this.out = new PrintWriter(out, false);
			this.err = new PrintWriter(err, false);
		}

		public final void setInputStream(InputStream in) {
			this.in = in;
		}

		public final void setInputStream(File in) {
			try {
				this.in = new FileInputStream(in);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		public final void setOutputStream(PrintStream out) {
			this.out = new PrintWriter(out, false);
		}

		public final void setOutputStream(File out) {
			try {
				this.out = new PrintWriter(new FileOutputStream(out), false);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		public final void setErrorStream(PrintStream err) {
			this.err = new PrintWriter(err, false);
		}

		public final void setErrorStream(File err) {
			try {
				this.err = new PrintWriter(new FileOutputStream(err), false);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
		}

		public final void setAutoFlush(boolean flush) {
			autoFlush = flush;
		}

		private boolean hasNextByte() {
			if (read < length) return true;
			read = 0;
			try {
				length = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return length > 0;
		}

		private int readByte() {
			return hasNextByte() ? buffer[read++] : -1;
		}

		private static boolean isPrintableChar(int c) {
			return 33 <= c && c <= 126;
		}

		private static boolean isNumber(int c) {
			return '0' <= c && c <= '9';
		}

		public final boolean hasNext() {
			while (hasNextByte() && !isPrintableChar(buffer[read])) read++;
			return hasNextByte();
		}

		public final char nextChar() {
			if (!hasNextByte())  throw new NoSuchElementException();
			return (char)readByte();
		}

		public final char[][] nextChar(int height) {
			char[][] ret = new char[height][];
			for (int i = 0;i < ret.length;++ i) ret[i] = next().toCharArray();
			return ret;
		}

		public final String next() {
			if (!hasNext()) throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b;
			while (isPrintableChar(b = readByte())) sb.appendCodePoint(b);
			return sb.toString();
		}

		public final String nextLine() {
			StringBuilder sb = new StringBuilder();
			int b;
			while(!isPrintableChar(b = readByte()));
			do sb.appendCodePoint(b); while(isPrintableChar(b = readByte()) || b == ' ');
			return sb.toString();
		}

		public final long nextLong() {
			if (!hasNext()) throw new NoSuchElementException();
			long n = 0;
			boolean minus = false;
			int b = readByte();
			if (b == '-') {
				minus = true;
				b = readByte();
			}
			if (!isNumber(b)) throw new NumberFormatException();
			while (true) {
				if (isNumber(b)) {
					n *= 10;
					n += b - '0';
				} else if (b == -1 || !isPrintableChar(b)) return minus ? -n : n;
				else throw new NumberFormatException();
				b = readByte();
			}
		}

		public final int nextInt() {
			long nl = nextLong();
			if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE) throw new NumberFormatException();
			return (int) nl;
		}

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

		public final int[] nextInt(int width) {
			int[] ret = new int[width];
			for (int i = 0;i < width;++ i) ret[i] = nextInt();
			return ret;
		}

		public final int[] nextInts() {
			return nextInts(" ");
		}

		public final int[] nextInts(String parse) {
			String[] get = nextLine().split(parse);
			int[] ret = new int[get.length];
			for (int i = 0;i < ret.length;++ i) ret[i] = Integer.valueOf(get[i]);
			return ret;
		}

		public final long[] nextLong(int width) {
			long[] ret = new long[width];
			for (int i = 0;i < width;++ i) ret[i] = nextLong();
			return ret;
		}

		public final long[] nextLongs() {
			return nextLongs(" ");
		}

		public final long[] nextLongs(String parse) {
			String[] get = nextLine().split(parse);
			long[] ret = new long[get.length];
			for (int i = 0;i < ret.length;++ i) ret[i] = Long.valueOf(get[i]);
			return ret;
		}

		public final int[][] nextInt(int width, int height) {
			int[][] ret = new int[height][width];
			for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[i][j] = nextInt();
			return ret;
		}

		public final long[][] nextLong(int width, int height) {
			long[][] ret = new long[height][width];
			for (int i = 0, j;i < height;++ i) for (j = 0;j < width;++ j) ret[j][i] = nextLong();
			return ret;
		}

		public final boolean[] nextBoolean(char T) {
			char[] s = next().toCharArray();
			boolean[] ret = new boolean[s.length];
			for (int i = 0;i < ret.length;++ i) ret[i] = s[i] == T;
			return ret;
		}

		public final boolean[][] nextBoolean(char T, int height) {
			boolean[][] ret = new boolean[height][];
			for (int i = 0;i < ret.length;++ i) {
				char[] s = next().toCharArray();
				ret[i] = new boolean[s.length];
				for (int j = 0;j < ret[i].length;++ j) ret[i][j] = s[j] == T;
			}
			return ret;
		}

		public final Point nextPoint() {
			return new Point(nextInt(), nextInt());
		}

		public final Point[] nextPoint(int width) {
			Point[] ret = new Point[width];
			for (int i = 0;i < width;++ i) ret[i] = nextPoint();
			return ret;
		}

		@Override
		protected void finalize() throws Throwable {
			try {
				super.finalize();
			} finally {
				in.close();
				out.close();
				err.close();
			}
		}

		public final boolean print(boolean b) {
			out.print(b);
			if (autoFlush) flush();
			return b;
		}

		public final Object print(boolean b, Object t, Object f) {
			return b ? print(t) : print(f);
		}

		public final char print(char c) {
			out.print(c);
			if (autoFlush) flush();
			return c;
		}

		public final char[] print(char[] s) {
			out.print(s);
			return s;
		}

		public final double print(double d) {
			out.print(d);
			if (autoFlush) flush();
			return d;
		}

		public final double print(double d, int length) {
			if (d < 0) {
				out.print('-');
				d = -d;
			}
			d += Math.pow(10, -length) / 2;
			out.print((long)d);
			out.print('.');
			d -= (long)d;
			for (int i = 0;i < length;++ i) {
				d *= 10;
				out.print((int)d);
				d -= (int)d;
			}
			if (autoFlush) flush();
			return d;
		}

		public final float print(float f) {
			out.print(f);
			if (autoFlush) flush();
			return f;
		}

		public final int print(int i) {
			out.print(i);
			if (autoFlush) flush();
			return i;
		}

		public final long print(long l) {
			out.print(l);
			if (autoFlush) flush();
			return l;
		}

		public final Object print(Object obj) {
			if (obj.getClass().isArray()) {
				if (obj instanceof boolean[][]) print(obj, "\n", " ");
				else if (obj instanceof byte[][]) print(obj, "\n", " ");
				else if (obj instanceof short[][]) print(obj, "\n", " ");
				else if (obj instanceof int[][]) print(obj, "\n", " ");
				else if (obj instanceof long[][]) print(obj, "\n", " ");
				else if (obj instanceof float[][]) print(obj, "\n", " ");
				else if (obj instanceof double[][]) print(obj, "\n", " ");
				else if (obj instanceof char[][]) print(obj, "\n", " ");
				else if (obj instanceof Object[][]) print(obj, "\n", " ");
				else print(obj, " ");
			} else {
				out.print(obj);
				if (autoFlush) flush();
			}
			return obj;
		}

		public final String print(String s) {
			out.print(s);
			if (autoFlush) flush();
			return s;
		}

		public final Object print(Object array, String... parse) {
			print(array, 0, parse);
			if (autoFlush) flush();
			return array;
		}

		private final Object print(Object array, int check, String... parse) {
			if (check >= parse.length) {
				if (array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension");
				print(array);
				return array;
			}
			String str = parse[check];
			if (array instanceof Object[]) {
				Object[] obj = (Object[]) array;
				if (obj.length == 0) return array;
				print(obj[0], check + 1, parse);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i], check + 1, parse);
				}
				return array;
			}
			if (array instanceof Collection) {
				Iterator<?> iter = ((Collection<?>)array).iterator();
				if (!iter.hasNext()) return array;
				print(iter.next(), check + 1, parse);
				while(iter.hasNext()) {
					print(str);
					print(iter.next(), check + 1, parse);
				}
				return array;
			}
			if (!array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension");
			if (check != parse.length - 1) throw new IllegalArgumentException("not equal dimension");
			if (array instanceof boolean[]) {
				boolean[] obj = (boolean[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else if (array instanceof byte[]) {
				byte[] obj = (byte[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
				return array;
			} else if (array instanceof short[]) {
				short[] obj = (short[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else if (array instanceof int[]) {
				int[] obj = (int[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else if (array instanceof long[]) {
				long[] obj = (long[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else if (array instanceof float[]) {
				float[] obj = (float[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else if (array instanceof double[]) {
				double[] obj = (double[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else if (array instanceof char[]) {
				char[] obj = (char[]) array;
				if (obj.length == 0) return array;
				print(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					print(str);
					print(obj[i]);
				}
			} else throw new AssertionError();
			return array;
		}

		public final Object[] print(String parse, Object... args) {
			print(args[0]);
			for (int i = 1;i < args.length;++ i) {
				print(parse);
				print(args[i]);
			}
			return args;
		}

		public final Object[] printf(String format, Object... args) {
			out.printf(format, args);
			if (autoFlush) flush();
			return args;
		}

		public final Object printf(Locale l, String format, Object... args) {
			out.printf(l, format, args);
			if (autoFlush) flush();
			return args;
		}

		public final void println() {
			out.println();
			if (autoFlush) flush();
		}

		public final boolean println(boolean b) {
			out.println(b);
			if (autoFlush) flush();
			return b;
		}

		public final Object println(boolean b, Object t, Object f) {
			return b ? println(t) : println(f);
		}

		public final char println(char c) {
			out.println(c);
			if (autoFlush) flush();
			return c;
		}

		public final char[] println(char[] s) {
			out.println(s);
			if (autoFlush) flush();
			return s;
		}

		public final double println(double d) {
			out.println(d);
			if (autoFlush) flush();
			return d;
		}

		public final double println(double d, int length) {
			print(d, length);
			println();
			return d;
		}

		public final float println(float f) {
			out.println(f);
			if (autoFlush) flush();
			return f;
		}

		public final int println(int i) {
			out.println(i);
			if (autoFlush) flush();
			return i;
		}

		public final long println(long l) {
			out.println(l);
			if (autoFlush) flush();
			return l;
		}

		public final Object println(Object obj) {
			print(obj);
			println();
			return obj;
		}

		public final String println(String s) {
			out.println(s);
			if (autoFlush) flush();
			return s;
		}

		public final Object println(Object array, String... parse) {
			print(array, parse);
			println();
			return array;
		}

		public final boolean debug(boolean b) {
			err.print(b);
			if (autoFlush) flush();
			return b;
		}

		public final Object debug(boolean b, Object t, Object f) {
			return b ? debug(t) : debug(f);
		}

		public final char debug(char c) {
			err.print(c);
			if (autoFlush) flush();
			return c;
		}

		public final char[] debug(char[] s) {
			err.print(s);
			return s;
		}

		public final double debug(double d) {
			err.print(d);
			if (autoFlush) flush();
			return d;
		}

		public final double debug(double d, int length) {
			if (d < 0) {
				err.print('-');
				d = -d;
			}
			d += Math.pow(10, -length) / 2;
			err.print((long)d);
			err.print('.');
			d -= (long)d;
			for (int i = 0;i < length;++ i) {
				d *= 10;
				err.print((int)d);
				d -= (int)d;
			}
			if (autoFlush) flush();
			return d;
		}

		public final float debug(float f) {
			err.print(f);
			if (autoFlush) flush();
			return f;
		}

		public final int debug(int i) {
			err.print(i);
			if (autoFlush) flush();
			return i;
		}

		public final long debug(long l) {
			err.print(l);
			if (autoFlush) flush();
			return l;
		}

		public final Object debug(Object obj) {
			if (obj.getClass().isArray()) {
				if (obj instanceof boolean[][]) debug(obj, "\n", " ");
				else if (obj instanceof byte[][]) debug(obj, "\n", " ");
				else if (obj instanceof short[][]) debug(obj, "\n", " ");
				else if (obj instanceof int[][]) debug(obj, "\n", " ");
				else if (obj instanceof long[][]) debug(obj, "\n", " ");
				else if (obj instanceof float[][]) debug(obj, "\n", " ");
				else if (obj instanceof double[][]) debug(obj, "\n", " ");
				else if (obj instanceof char[][]) debug(obj, "\n", " ");
				else if (obj instanceof Object[][]) debug(obj, "\n", " ");
				else debug(obj, " ");
			} else {
				err.print(obj);
				if (autoFlush) flush();
			}
			return obj;
		}

		public final String debug(String s) {
			err.print(s);
			if (autoFlush) flush();
			return s;
		}

		public final Object debug(Object array, String... parse) {
			debug(array, 0, parse);
			if (autoFlush) flush();
			return array;
		}

		private final Object debug(Object array, int check, String... parse) {
			if (check >= parse.length) {
				if (array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension");
				debug(array);
				return array;
			}
			String str = parse[check];
			if (array instanceof Object[]) {
				Object[] obj = (Object[]) array;
				if (obj.length == 0) return array;
				debug(obj[0], check + 1, parse);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i], check + 1, parse);
				}
				return array;
			}
			if (array instanceof Collection) {
				Iterator<?> iter = ((Collection<?>)array).iterator();
				if (!iter.hasNext()) return array;
				debug(iter.next(), check + 1, parse);
				while(iter.hasNext()) {
					debug(str);
					debug(iter.next(), check + 1, parse);
				}
				return array;
			}
			if (!array.getClass().isArray()) throw new IllegalArgumentException("not equal dimension");
			if (check != parse.length - 1) throw new IllegalArgumentException("not equal dimension");
			if (array instanceof boolean[]) {
				boolean[] obj = (boolean[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else if (array instanceof byte[]) {
				byte[] obj = (byte[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
				return array;
			} else if (array instanceof short[]) {
				short[] obj = (short[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else if (array instanceof int[]) {
				int[] obj = (int[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else if (array instanceof long[]) {
				long[] obj = (long[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else if (array instanceof float[]) {
				float[] obj = (float[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else if (array instanceof double[]) {
				double[] obj = (double[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else if (array instanceof char[]) {
				char[] obj = (char[]) array;
				if (obj.length == 0) return array;
				debug(obj[0]);
				for (int i = 1;i < obj.length;++ i) {
					debug(str);
					debug(obj[i]);
				}
			} else throw new AssertionError();
			return array;
		}

		public final Object[] debug(String parse, Object... args) {
			debug(args[0]);
			for (int i = 1;i < args.length;++ i) {
				debug(parse);
				debug(args[i]);
			}
			return args;
		}

		public final Object[] debugf(String format, Object... args) {
			err.printf(format, args);
			if (autoFlush) flush();
			return args;
		}

		public final Object debugf(Locale l, String format, Object... args) {
			err.printf(l, format, args);
			if (autoFlush) flush();
			return args;
		}

		public final void debugln() {
			err.println();
			if (autoFlush) flush();
		}

		public final boolean debugln(boolean b) {
			err.println(b);
			if (autoFlush) flush();
			return b;
		}

		public final Object debugln(boolean b, Object t, Object f) {
			return b ? debugln(t) : debugln(f);
		}

		public final char debugln(char c) {
			err.println(c);
			if (autoFlush) flush();
			return c;
		}

		public final char[] debugln(char[] s) {
			err.println(s);
			if (autoFlush) flush();
			return s;
		}

		public final double debugln(double d) {
			err.println(d);
			if (autoFlush) flush();
			return d;
		}

		public final double debugln(double d, int length) {
			debug(d, length);
			debugln();
			return d;
		}

		public final float debugln(float f) {
			err.println(f);
			if (autoFlush) flush();
			return f;
		}

		public final int debugln(int i) {
			err.println(i);
			if (autoFlush) flush();
			return i;
		}

		public final long debugln(long l) {
			err.println(l);
			if (autoFlush) flush();
			return l;
		}

		public final Object debugln(Object obj) {
			debug(obj);
			debugln();
			return obj;
		}

		public final String debugln(String s) {
			err.println(s);
			if (autoFlush) flush();
			return s;
		}

		public final Object debugln(Object array, String... parse) {
			debug(array, parse);
			debugln();
			return array;
		}

		public final void flush() {
			out.flush();
			err.flush();
		}
	}
}

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.


import java.util.*;
import java.io.*;

public class Main {
    //static long ans = 0;
    static long[] c;
    static long[][] dc;
    static int[] last;
    public static void main(String[] args) throws Exception {
        FastScanner sc = new FastScanner(System.in);
        int d = sc.nextInt();
        c = sc.nextLongArray(26);
        dc = new long[d][26];
        last = new int[26];
        int[] schedule = new int[d];
        for(int i = 0; i < d; i++){
            long maxV = -Integer.MAX_VALUE;
            int max = 0;
            for(int j = 0; j < 26; j++){
                dc[i][j] = sc.nextInt();
                if(maxV < dc[i][j]){
                    maxV = dc[i][j] + (c[j] * (i-last[j]));
                    max = j;
                }
            }
            schedule[i] = max;
            last[max] = i;
        }
        int[] top = new int[d];
        Arrays.fill(top,0);
        long topscore = -Integer.MAX_VALUE;
        schedule[0] = 0;
        last = new int[26];
        last[0] = 1;
        for(int k = 1; k < d; k++){
            long maxV = -Integer.MAX_VALUE;
            int max = 0;
            for(int j = 0; j < 26; j++){
                if(maxV < dc[k][j]){
                    maxV = dc[k][j] + (c[j] * (k-last[j]));
                    max = j;
                }
            }
            schedule[k] = max;
            last[max] = k;
        }
        long score = checkAns(schedule);
        if(score > topscore){
            topscore = score;
            top = schedule.clone();
        }
        for(int i = 0; i <= 270000; i++){
            int[] tmp = top.clone();
            int di = (int)(Math.random()*d);
            int ci = (int)(Math.random()*26);
            tmp[di] = ci;
            score = checkAns(tmp);
            if(score > topscore){
                topscore = score;
                top[di] = ci;
            }
        }
        printSchedule(top);
    }

    public static long checkAns(int[] s){
        int d = s.length;
        last = new int[26];
        long ans = 0;
        for(int i = 0; i < d; i++){
            int hold = s[i];
            last[hold] = i+1;
            ans += dc[i][hold];
            ans = calc(i+1,ans);
        }
        return ans;
    }

    public static long calc(int d, long ans){
        for(int i = 0; i < 26; i++){
            ans -= c[i] * (d-last[i]);
        }
        return ans;
    }

    public static void printSchedule(int[] schedule){
        for(int d : schedule){
            System.out.println(d+1);
        }
        return;
    }
}

class FastScanner {
    private BufferedReader reader = null;
    private StringTokenizer tokenizer = null;
    public FastScanner(InputStream in) {
        reader = new BufferedReader(new InputStreamReader(in));
        tokenizer = null;
    }

    public String next() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                tokenizer = new StringTokenizer(reader.readLine());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken();
    }

    public String nextLine() {
        if (tokenizer == null || !tokenizer.hasMoreTokens()) {
            try {
                return reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenizer.nextToken("\n");
    }

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

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

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

    public String[] nextArray(int n) {
        String[] a = new String[n];
        for (int i = 0; i < n; i++)
            a[i] = next();
        return a;
    }

    public int[] nextIntArray(int n) {
        int[] a = new int[n];
        for (int i = 0; i < n; i++)
            a[i] = nextInt();
        return a;
    }

    public long[] nextLongArray(int n) {
        long[] a = new long[n];
        for (int i = 0; i < n; i++)
            a[i] = nextLong();
        return a;
    }
}


import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        int D = sc.nextInt();
        int[] c = new int[27];
        int[] t = new int[D + 1];
        int[] last_day = new int[27];
        Arrays.fill(last_day, 0);
        int[][] s = new int[D + 1][27];
        for (int i = 1; i <= 26; i++) {
            c[i] = sc.nextInt();
        }
        for (int i = 1; i <= D; i++) {
            for (int j = 1; j <= 26; j++) {
                s[i][j] = sc.nextInt();
            }
        }
        Random random =new Random();
        for (int i = 1; i <= D; i++) {
            t[i] = 1+random.nextInt(26);
        }
        int[] tmp_array = t;
        long tmp_sum = 0;
        long last_sum =0;
        for (int j = 0; j < 9; j++) {
            int d = 1+random.nextInt(D);
            int q = 1+random.nextInt(D);
            t[d] = t[q];
            for (int i = 1; i <= D; i++) {
                last_day[t[i]] = i;
                tmp_sum += calcS(c, s, t[i], i, last_day);
            }
            if(tmp_sum>last_sum){
                continue;
            }else {
                t = tmp_array;
            }
        }

        for (int i = 1; i <= D; i++) {
            System.out.println(t[i]);
        }

    }

    private static long calcS(int[] c, int[][] s, int kaisai, int day, int[] last_day) {

        long loss = 0;
        for (int i = 1; i <= 26; i++) {
            if (i == kaisai) {
                last_day[i] = day;
                continue;
            }
            loss -= c[i] * (day - last_day[i]);
        }

        long plus = s[day][kaisai];
        return plus + loss;
    }

}


import java.util.*;
public class Main {

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		int INF = Integer.MAX_VALUE/2;
		StringBuilder ans = new StringBuilder();
		Scanner sc = new Scanner(System.in);
		int D = Integer.parseInt(sc.next());
		int[] c = new int[26];
		Arrays.setAll(c, i -> Integer.parseInt(sc.next()));
		int[][] s = new int[D][26];
		for(int i = 0; i < D; i++)
			Arrays.setAll(s[i], x -> Integer.parseInt(sc.next()));
		int[] con = new int[D];
		TreeSet<Integer>[] used = new TreeSet[26];
		for(int i = 0; i < 26; i++) {
			used[i] = new TreeSet<Integer>();
			used[i].add(-1);
		}
		int sat = 0;
		for(int d = 0; d < D; d++) {
			int max = -INF, now = 0;
			for(int i = 0; i < 26; i++) {
				int temp = 0;
				temp += s[d][i];
				for(int j = 0; j < 26; j++)
					if(i != j)
						temp -= c[j] * (d - used[j].last());
				if(max < temp) {
					max = temp;
					now = i;
				}
			}
			con[d] = now;
			used[now].add(d);
			sat += max;
		}
		for(int i = 0; i < 26; i++)
			used[i].add(D);
		Random r = new Random();
		while(true) {
			int d = r.nextInt(D);
			for(int q = 0; q < 26; q++) {
				int temp = 0;
				temp -= s[d][con[d]];
				temp += s[d][q];
				temp -= c[con[d]] * (used[con[d]].ceiling(d) - d) * (d - used[con[d]].lower(d));
				temp += c[q] * (d - used[q].lower(d)) * (used[q].ceiling(d) - d);
				if(temp > 0) {
					sat += temp;
					con[d] = q;
					used[con[d]].remove(d);
					used[q].add(d);
				}
			}
			if(System.currentTimeMillis() - start > 1850)
				break;
		}
		for(int i : con)
			ans.append((i+1) + "\n");
		System.out.println(ans);
	}

}


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.NoSuchElementException;
import java.util.PriorityQueue;
import java.util.Set;

/**
 * Introduction to Heuristics Contest
 * @author tsukammo
 */
public class Main {

	// only call
	public static void main(String[] args) throws IOException {
		if (submit) {
			out = new PrintWriter(System.out);
		} else {
			out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
		}
		new Main().run();
		out.flush();
	}

	// variables
	int D, T;
	int[] c;
	int[][] s;
	int[] preOpen;
	Node ans;
	Set<Integer> loopCheck = new HashSet<>();

	int[] dx = new int[] { 0, 0, -1, 1 };
	int[] dy = new int[] { -1, 1, 0, 0 };
	int[] dxR = new int[] { 0, 0, 1, -1 };
	int[] dyR = new int[] { 1, -1, 0, 0 };
	int[] dR = new int[] { 1, 0, 3, 2 };

	void run() {
		input();
		init();
		solve();
		output();
	}

	long timeLimit = 1_900;

	void solve() {
		Node now = new Node(D);
		now.eval();
		int trueScore = now.score;
		ans = now;
		System.err.println("first=" + now.score);
		now.evalTmp(null);
		int tmpScore = now.score;
		int checkSum = 0;
		for (int i = 0; i < T; i++) {
			checkSum += now.scoreC[i];
		}
		System.err.println("tmpScore=" + now.score + " " + checkSum);
		long currentTime = System.currentTimeMillis();
		int loopCount = 0;
		double forceLine;
		while (currentTime < et) {
			loopCount++;
			int r = rnd.nextInt(2);
			//int r = 0;
			int cd = -1;
			int ct = -1;
			switch (r) {
			case 0:
				cd = rnd.nextInt(D);
				ct = rnd.nextInt(T);
				while (now.contests[cd] == ct) {
					cd = rnd.nextInt(D);
					ct = rnd.nextInt(T);
				}
				tmpScore = now.evalChange(cd, ct);
				break;
			case 1:
				cd = rnd.nextInt(D - 1);
				tmpScore = now.evalSwap(cd);
				break;
			}

			currentTime = System.currentTimeMillis();
			forceLine = (et - currentTime) / C;
			if (now.score <= tmpScore || forceLine > rnd.nextDouble()) {
				now.score = tmpScore;

				switch (r) {
				case 0:
					now.stateChange(cd, ct);
					break;
				case 1:
					now.stateSwap(cd);
					break;
				}
			} else {
				// rollback
			}
		}
		checkSum = 0;
		for (int i = 0; i < T; i++) {
			checkSum += now.scoreC[i];
		}
		now.eval();
		System.err.println("final=" + now.score + " " + checkSum);
		System.err.println("loop=" + loopCount);
		System.err.println("solve END.");
	}

	void output() {
		for (int i = 0; i < D; i++) {
			out.println(ans.contests[i] + 1);
		}
	}

	char getCharD(byte d) {
		switch (d) {
		case 0:
			return 'U';
		case 1:
			return 'D';
		case 2:
			return 'L';
		case 3:
			return 'R';

		default:
			break;
		}
		return '_';
	}

	/**
	 * 計算用に編集
	 */
	void init() {
		preOpen = new int[T];
	}

	/**
	 * 素直に持つ
	 */
	void input() {
		D = in.nextInt();
		st = System.currentTimeMillis();
		et = st + timeLimit;
		T = 26;
		c = new int[T];
		for (int i = 0; i < T; i++) {
			c[i] = in.nextInt();
		}
		s = new int[D][T];
		for (int i = 0; i < D; i++) {
			for (int j = 0; j < T; j++) {
				s[i][j] = in.nextInt();
			}
		}
		System.err.println("input END.");
	}

	// param
	final byte GOAL = -9;
	final byte NONE = -1;
	final byte INF = 100;
	final byte BLOCK = 111;
	final long C = TL * 10_000;
	final int X = 1000; // 厳密な精度は不要と考え、小数点以下を簡略化するための桁増し。
	final int SCORE_D = -10;
	final int SCORE_D2 = -9;
	final int SCORE_C = 1;
	final int SCORE_R = 1000;
	final int SPEED_CAR = 250;
	final int SPEED_DOLLY = 100;
	final int PRIME_TIME_LIMIT = 240;
	final int ROLLY_LIMIT = 10;
	final int POINT_DELIVERY = 10000;
	final int M2S = 60;
	int TIME_LIMIT;
	int TIME_LIMIT_2;

	// predefined
	FastScanner in = new FastScanner(System.in);
	static PrintWriter out = new PrintWriter(System.out);
	static final String FILE_PATH = ".\\";
	static File file = new File(FILE_PATH + "result.out");
	long st = 0, et = 0;
	public Random rnd = new Random(19881221L);

	ArrayList<Integer> list = new ArrayList<>();
	ArrayDeque<P> q = new ArrayDeque<>();
	ArrayDeque<P> q2 = new ArrayDeque<>();

	// 2D-map
	final int[] dw = new int[] { 0, 1, 0, -1, 1, 1, -1, -1 };
	final int[] dh = new int[] { 1, 0, -1, 0, 1, -1, 1, -1 };

	// search
	PriorityQueue<Node> pq = new PriorityQueue<>();

	int[] preDay = new int[] { -1, -1 };

	class Node implements Comparable<Node> {

		int score;
		int[] scoreC;
		int[] contests;

		public Node(int N) {
			this.score = 0;
			scoreC = new int[T];
			contests = new int[N];
			for (int i = 0; i < contests.length; i++) {
				// 初期解
				contests[i] = rnd.nextInt(T);
			}
			// TODO
			/*
			contests[0] = 0;
			contests[1] = 16;
			contests[2] = 12;
			contests[3] = 13;
			contests[4] = 12;
			*/
		}

		int evalSwap(int d) {
			int ret = this.score;
			int before = this.contests[d];
			int after = this.contests[d + 1];
			ret -= this.scoreC[before];
			ret -= this.scoreC[after];
			Arrays.fill(preDay, -1);
			for (int i = 0; i < D; i++) {
				int t = this.contests[i];
				if (i == d) {
					ret += s[i][after];
					preDay[1] = i;
				} else if (i == d + 1) {
					ret += s[i][before];
					preDay[0] = i;
				} else {
					if (t == before) {
						ret += s[i][t];
						preDay[0] = i;
					} else if (t == after) {
						ret += s[i][t];
						preDay[1] = i;
					}
				}
				ret -= c[before] * (i - preDay[0]);
				ret -= c[after] * (i - preDay[1]);
			}
			return ret;
		}

		void stateSwap(int d) {
			int before = this.contests[d];
			int after = this.contests[d + 1];
			this.contests[d] = after;
			this.contests[d + 1] = before;
			this.scoreC[before] = 0;
			this.scoreC[after] = 0;

			Arrays.fill(preDay, -1);
			for (int i = 0; i < D; i++) {
				int t = this.contests[i];
				if (t == before) {
					this.scoreC[before] += s[i][t];
					preDay[0] = i;
				} else if (t == after) {
					this.scoreC[after] += s[i][t];
					preDay[1] = i;
				}
				this.scoreC[before] -= c[before] * (i - preDay[0]);
				this.scoreC[after] -= c[after] * (i - preDay[1]);
			}
		}

		int evalChange(int cd, int ct) {
			int ret = this.score;
			int before = this.contests[cd];
			ret -= this.scoreC[before];
			ret -= this.scoreC[ct];
			Arrays.fill(preDay, -1);
			for (int i = 0; i < D; i++) {
				int t = this.contests[i];
				if (i == cd) {
					ret += s[i][ct];
					preDay[1] = i;
				} else {
					if (t == before) {
						ret += s[i][t];
						preDay[0] = i;
					} else if (t == ct) {
						ret += s[i][t];
						preDay[1] = i;
					}
				}
				ret -= c[before] * (i - preDay[0]);
				ret -= c[ct] * (i - preDay[1]);
			}
			return ret;
		}

		void stateChange(int cd, int ct) {
			int before = this.contests[cd];
			this.contests[cd] = ct;
			this.scoreC[before] = 0;
			this.scoreC[ct] = 0;

			Arrays.fill(preDay, -1);
			for (int i = 0; i < D; i++) {
				int t = this.contests[i];
				if (t == before) {
					this.scoreC[before] += s[i][t];
					preDay[0] = i;
				} else if (t == ct) {
					this.scoreC[ct] += s[i][t];
					preDay[1] = i;
				}
				this.scoreC[before] -= c[before] * (i - preDay[0]);
				this.scoreC[ct] -= c[ct] * (i - preDay[1]);
			}
			//this.score += this.scoreC[before];
			//this.score += this.scoreC[ct];
		}

		public Node(Node n) {
			this.score = n.score;
			this.contests = Arrays.copyOf(n.contests, D);
		}

		public int eval() {
			this.score = 0;
			Arrays.fill(scoreC, 0);
			Arrays.fill(preOpen, -1);
			for (int i = 0; i < D; i++) {
				int t = this.contests[i];
				score += s[i][t];
				scoreC[t] += s[i][t];
				preOpen[t] = i;
				for (int j = 0; j < T; j++) {
					int tmp = c[j] * (i - preOpen[j]);
					score -= tmp;
					scoreC[j] -= tmp;
				}
			}
			return this.score;
		}

		public void evalTmp(byte[][][] nowStep) {
			// TODO
		}

		@Override
		public int compareTo(Node o) {
			return Integer.compare(this.score, o.score);
		}

	}

	int valid(int p) {
		if (p == -1) {
			return D - 1;
		}
		if (p == D) {
			return 0;
		}
		return p;
	}

	int changeD(int d, byte b) {
		switch (b) {
		case 0:
			return 0;
		case 1:
			return 1;
		case 2:
			return 2;
		case 3:
			return 3;
		default:
			break;
		}
		return d;
	}

	// object
	class P {
		int y, x;

		public P(int y, int x) {
			this.y = y;
			this.x = x;
		}

		public P(P p) {
			this.y = p.y;
			this.x = p.x;
		}

		P nextP(int d) {
			int ny = valid(y + dy[d]);
			int nx = valid(x + dx[d]);
			return new P(ny, nx);
		}

		public String toString() {
			return y + " " + x;
		}
	}

	class D {
		P p;
		byte d;

		public D(P p, int d) {
			this.p = p;
			this.d = (byte) d;
		}

		public D(D d) {
			this.p = new P(d.p);
			this.d = d.d;
		}

		public String toString() {
			return p.y + " " + p.x + " " + d;
		}
	}

	// library
	class FastScanner {
		private final InputStream in;
		private final byte[] buffer = new byte[1024];
		private int ptr = 0;
		private int buflen = 0;

		FastScanner(InputStream in) {
			this.in = in;
		}

		private boolean hasNextByte() {
			if (ptr < buflen) {
				return true;
			} else {
				ptr = 0;
				try {
					buflen = in.read(buffer);
				} catch (IOException e) {
					e.printStackTrace();
				}
				if (buflen <= 0) {
					return false;
				}
			}
			return true;
		}

		private int readByte() {
			if (hasNextByte())
				return buffer[ptr++];
			else
				return -1;
		}

		private boolean isPrintableChar(int c) {
			return 33 <= c && c <= 126;
		}

		public boolean hasNext() {
			while (hasNextByte() && !isPrintableChar(buffer[ptr]))
				ptr++;
			return hasNextByte();
		}

		public String next() {
			if (!hasNext())
				throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b = readByte();
			while (isPrintableChar(b)) {
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}

		public long nextLong() {
			if (!hasNext())
				throw new NoSuchElementException();
			long n = 0;
			boolean minus = false;
			int b = readByte();
			if (b == '-') {
				minus = true;
				b = readByte();
			}
			if (b < '0' || '9' < b) {
				throw new NumberFormatException();
			}
			while (true) {
				if ('0' <= b && b <= '9') {
					n *= 10;
					n += b - '0';
				} else if (b == -1 || !isPrintableChar(b)) {
					return minus ? -n : n;
				} else {
					throw new NumberFormatException();
				}
				b = readByte();
			}
		}

		public int nextInt() {
			long nl = nextLong();
			if (nl < Integer.MIN_VALUE || nl > Integer.MAX_VALUE)
				throw new NumberFormatException();
			return (int) nl;
		}

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

	class Random {
		private long seed;
		private final long multiplier = 0x5DEECE66DL, addend = 0xBL, mask = (1L << 48) - 1;
		int bits, val;

		Random(long seed) {
			this.seed = seed;
		}

		int nextInt(int n) {
			do {
				bits = (int) ((seed = (seed * multiplier + addend) & mask) >>> 17);
				val = bits % n;
			} while (bits - val + (n - 1) < 0);
			return val;
		}

		double nextDouble() {
			return nextInt(10000000) / 10000000.0;
		}
	}

	static long TL = 1000;
	static boolean submit = true;
}


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

		int d = sc.nextInt();

		int[] c = new int[27];
		for ( int i=1; i<27; i++ ) {
			c[i] = sc.nextInt();
		}

		int[][] s = new int[d][27];
		for ( int i=0; i<d; i++ ) {
		for ( int j=1; j<27; j++ ) {
			s[i][j] = sc.nextInt();
		}
		}

		int[] last = new int[27];
		for ( int i=0; i<d; i++ ) {
			int t = 0;
			int man = -999999999;

			for ( int j=1; j<27; j++ ) {
				int manj = 0;
				for ( int k=1; k<27; k++ ) {
					if ( j==k ) {
						manj += s[i][j];
					} else {
						manj -= (c[k]*((i+1)-last[k]));
					}
				}

				if ( manj>man ) {
					man = manj;
					t = j;
				}
			}

			last[t] = i+1;
			System.out.println(t);
		}

	}
}


import java.util.*;

public class Main {

    public static void main(String args []) {

        Scanner scan = new Scanner(System.in);

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

        long a[] = new long[n+1];
        long b[] = new long[m+1];
        long asum[] = new long[n+1];
        long bsum[] = new long[m+1];

        for (int i=1; i<=n; i++) {
            a[i] = scan.nextLong();

            asum[i] = asum[i-1] + a[i];
        }
        for (int i = 1; i<=m; i++) {
            b[i] = scan.nextLong();

            bsum[i] = bsum[i-1] + b[i];
        }

        int sum = 0;
        int j = m;

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

            if (a[i] > k) {
                continue;
            }

            while (b[j] > k - a[i]) {
                j--;
            }
            sum = Math.max(sum, i + j);
        }

        System.out.println(sum);

    }
}

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.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Objects;
import java.util.StringTokenizer;
import java.util.function.BiFunction;
import java.util.function.Function;

public class Main {

    static BiFunction<Integer, Integer, Integer> ADD = (x, y) -> (x + y);
    static BiFunction<ArrayList<Integer>, ArrayList<Integer>, ArrayList<Integer>> ADD_ARRAY_LIST = (x, y) -> {
        x.addAll(y);
        return x;
    };

    static Function<Pair<Integer, Integer>, Integer> GET_FIRST = (x) -> (x.first);
    static Function<Pair<Integer, Integer>, Integer> GET_SECOND = (x) -> (x.second);
    static Comparator<Pair<Integer, Integer>> C = Comparator.comparing(GET_FIRST).thenComparing(GET_SECOND);

    public static void main(String[] args) throws Exception {
        long startTime = System.nanoTime();
        int t = 1;
        while (t-- > 0) {
            solve();
        }
        long endTime = System.nanoTime();
        err.println("Execution Time : +" + (endTime - startTime) / 1000000 + " ms");
        exit(0);
    }

    static void solve() {
        int n = in.nextInt(), m = in.nextInt(), k = in.nextInt();
        long sum = 0;
        int[] A = in.readAllInts(n);
        int[] B = in.readAllInts(m);
        long[] AA = new long[n + 1];
        long[] AB = new long[m + 1];
        for (int i = 0; i < n; i++) {
            AA[i + 1] = AA[i] + A[i];
        }
        for (int i = 0; i < m; i++) {
            AB[i + 1] = AB[i] + B[i];
        }
        int ans = 0;
        for (int i = 1; i <= n; i++) {
            if (AA[i] <= k) {
                int j = upper_bound(AB, k - AA[i]);
                ans = Math.max(ans, i + j - 1);
            }
        }
        out.println(ans);
    }

    static int upper_bound(long[] ab, long i) {
        int l = 1;
        int r = ab.length-1;
        int mid;
        int ans = r;
        while (l <= r) {
            mid = (l + r) / 2;
            if (ab[mid] < i) {
                l = mid + 1;
            } else if (ab[mid] > i) {
                r = mid - 1;
                ans = mid;
            } else {
                r = mid - 1;
            }
        }
        return ans;
    }

    static void debug(Object... args) {
        for (Object a : args) {
            out.println(a);
        }
    }

    static void y() {
        out.println("YES");
    }

    static void n() {
        out.println("NO");
    }

    static <T> T min(T a, T b, Comparator<T> C) {
        if (C.compare(a, b) <= 0) {
            return a;
        }
        return b;
    }

    static <T> T max(T a, T b, Comparator<T> C) {
        if (C.compare(a, b) >= 0) {
            return a;
        }
        return b;
    }

    static void fail() {
        out.println("-1");
    }

    static class Pair<T, R> {
        public T first;
        public R second;

        public Pair(T first, R second) {
            this.first = first;
            this.second = second;
        }

        @Override
        public boolean equals(final Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }
            final Pair<?, ?> pair = (Pair<?, ?>) o;
            return Objects.equals(first, pair.first) && Objects.equals(second, pair.second);
        }

        @Override
        public int hashCode() {
            return Objects.hash(first, second);
        }

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

        public T getFirst() {
            return first;
        }

        public R getSecond() {
            return second;
        }
    }

    static <T, R> Pair<T, R> make_pair(T a, R b) {
        return new Pair<>(a, b);
    }

    static class ArrayUtils {

        static void swap(int[] a, int i, int j) {
            int temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }

        static void swap(char[] a, int i, int j) {
            char temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }

        static void print(char[] a) {
            for (char c : a) {
                out.print(c);
            }
            out.println("");
        }

        static int[] reverse(int[] data) {
            int[] p = new int[data.length];
            for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
                p[i] = data[j];
            }
            return p;
        }

        static void prefixSum(long[] data) {
            for (int i = 1; i < data.length; i++) {
                data[i] += data[i - 1];
            }
        }

        static void prefixSum(int[] data) {
            for (int i = 1; i < data.length; i++) {
                data[i] += data[i - 1];
            }
        }

        static long[] reverse(long[] data) {
            long[] p = new long[data.length];
            for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
                p[i] = data[j];
            }
            return p;
        }

        static char[] reverse(char[] data) {
            char[] p = new char[data.length];
            for (int i = 0, j = data.length - 1; i < data.length; i++, j--) {
                p[i] = data[j];
            }
            return p;
        }

        static int[] MergeSort(int[] A) {
            if (A.length > 1) {
                int q = A.length / 2;
                int[] left = new int[q];
                int[] right = new int[A.length - q];
                System.arraycopy(A, 0, left, 0, q);
                System.arraycopy(A, q, right, 0, A.length - q);
                int[] left_sorted = MergeSort(left);
                int[] right_sorted = MergeSort(right);
                return Merge(left_sorted, right_sorted);
            } else {
                return A;
            }
        }

        static int[] Merge(int[] left, int[] right) {
            int[] A = new int[left.length + right.length];
            int i = 0;
            int j = 0;
            for (int k = 0; k < A.length; k++) {
                // To handle left becoming empty
                if (i == left.length && j < right.length) {
                    A[k] = right[j];
                    j++;
                    continue;
                }
                // To handle right becoming empty
                if (j == right.length && i < left.length) {
                    A[k] = left[i];
                    i++;
                    continue;
                }
                if (left[i] <= right[j]) {
                    A[k] = left[i];
                    i++;
                } else {
                    A[k] = right[j];
                    j++;
                }
            }
            return A;
        }

        static long[] MergeSort(long[] A) {
            if (A.length > 1) {
                int q = A.length / 2;
                long[] left = new long[q];
                long[] right = new long[A.length - q];
                System.arraycopy(A, 0, left, 0, q);
                System.arraycopy(A, q, right, 0, A.length - q);
                long[] left_sorted = MergeSort(left);
                long[] right_sorted = MergeSort(right);
                return Merge(left_sorted, right_sorted);
            } else {
                return A;
            }
        }

        static long[] Merge(long[] left, long[] right) {
            long[] A = new long[left.length + right.length];
            int i = 0;
            int j = 0;
            for (int k = 0; k < A.length; k++) {
                // To handle left becoming empty
                if (i == left.length && j < right.length) {
                    A[k] = right[j];
                    j++;
                    continue;
                }
                // To handle right becoming empty
                if (j == right.length && i < left.length) {
                    A[k] = left[i];
                    i++;
                    continue;
                }
                if (left[i] <= right[j]) {
                    A[k] = left[i];
                    i++;
                } else {
                    A[k] = right[j];
                    j++;
                }
            }
            return A;
        }
    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 2048);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

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

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

        public int[] readAllInts(int n) {
            int[] p = new int[n];
            for (int i = 0; i < n; i++) {
                p[i] = in.nextInt();
            }
            return p;
        }

        public int[] readAllInts(int n, int s) {
            int[] p = new int[n + s];
            for (int i = s; i < n + s; i++) {
                p[i] = in.nextInt();
            }
            return p;
        }

        public long[] readAllLongs(int n) {
            long[] p = new long[n];
            for (int i = 0; i < n; i++) {
                p[i] = in.nextLong();
            }
            return p;
        }

        public long[] readAllLongs(int n, int s) {
            long[] p = new long[n + s];
            for (int i = s; i < n + s; i++) {
                p[i] = in.nextLong();
            }
            return p;
        }

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

    static void exit(int a) {
        out.close();
        err.close();
        System.exit(a);
    }

    static InputStream inputStream = System.in;
    static OutputStream outputStream = System.out;
    static OutputStream errStream = System.err;
    static InputReader in = new InputReader(inputStream);
    static PrintWriter out = new PrintWriter(outputStream);
    static PrintWriter err = new PrintWriter(errStream);
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

}


import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        long K = sc.nextLong();
        List<Long> aSum = new ArrayList<>();
        aSum.add((long) 0);
        List<Long> bSum = new ArrayList<>();
        bSum.add((long) 0);
        long tmp = 0;
        for (int i = 0; i < N; i++) {
            tmp += sc.nextLong();
            aSum.add(tmp);
        }
        tmp = 0;
        for (int i = 0; i < M; i++) {
            tmp += sc.nextLong();
            bSum.add(tmp);
        }
        int aInd = 0;
        int bInd = 0;
        long ans = 0;
        while (bSum.get(bInd) <= K) {
            bInd += 1;
            if (bInd == M) {
                break;
            }
        }

        while (true) {
            while (aInd <= N && aSum.get(aInd) + bSum.get(bInd) <= K) {
                aInd += 1;
            }
            if (aInd != 0) aInd -= 1;
            if (aSum.get(aInd) + bSum.get(bInd) <= K) {
                ans = Math.max(ans, aInd + bInd);
                if (aInd == N)
                    break;
                aInd += 1;
            }
            if (bInd == 0)
                break;
            while (aSum.get(aInd) + bSum.get(bInd) > K) {
                bInd -= 1;
                if (bInd == -1) {
                    bInd += 1;
                    break;
                }
            }
        }
        System.out.println(ans);
    }
}


import java.util.*;
public class Main {
    //変数定義
    static long [] SumB;
    static int M ;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        M = sc.nextInt();
        long K = sc.nextLong();
        long A[] = new long[N+1];
        long B[] = new long[M+1];
        long SumA[] = new long[N+1];
        SumA[0]=0;
        SumB = new long[M+1];
        SumB[0]=0;
        long Remain = 0;
        int wk=0;
        int ans=0;

        for(int i=1;i<=N;i++){
            A[i]=sc.nextLong();

            SumA[i]=SumA[i-1]+A[i];
        }

        for(int j=1;j<=M;j++){
            B[j]=sc.nextLong();

            SumB[j]=SumB[j-1]+B[j];
        }

        outside:for(int i=1;i<=N;i++){
            Remain = K-SumA[i];
            if (Remain>0) {
                //にぶたん
                //二分探索

                wk=i+(binarysearch((int)Remain));

                ans=Math.max(wk,ans);

            }

            else{
                //終了
                if (Remain==0) {
                    wk=i;
                }
                else{
                    wk=i-1;
                }
                ans=Math.max(wk,ans);
                break outside;
            }
        }

        System.out.println(ans);

    }

    //関数定義二分探
    public static int binarysearch(int key) {

        int left = 0;

        int right = SumB.length;

        while (right - left > 1) {

            int mid = left + (right - left) / 2;

            if (SumB[mid] > key){
            right = mid;

            }
            else{
            left = mid;
            }
        }

        /* left は条件を満たさない最大の値、right は条件を満たす最小の値になっている */
        return left;
    }

}


import java.util.*;
import java.io.*;

public class Main {

    public Main(FastScanner in, PrintWriter out, int test) {
        int N = in.nextInt();
        int M = in.nextInt();
        int K = in.nextInt();

        int[] A = new int[N];
        for (int i = 0; i < N; i++)
            A[i] = in.nextInt();

        int[] B = new int[M];
        for (int i = 0; i < M; i++)
            B[i] = in.nextInt();

        int res = 0, a = 0, b = 0;
        while (K > 0) {
            int t = 0;
            if (a < N && b < M) {
                t = A[a] <= B[b] ? A[a++] : B[b++];
            } else if (a < N) {
                t = A[a++];
            } else if (b < M) {
                t = B[b++];
            } else
                break;
            K -= t;
            if (K >= 0) res += 1;
        }
        out.println(res);
    }

    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out);
        // Scanner in = new Scanner(
                // new BufferedReader(new InputStreamReader(System.in)));
        FastScanner in = new FastScanner(System.in);

        // int T = in.nextInt();
        for (int t = 1; t <= 1; t++) {
            Main sol = new Main(in, out, t);
        }

        out.close();
    }
}

class FastScanner{
    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;

    public FastScanner(InputStream stream)
    {
        this.stream = stream;
    }

    int read()
    {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars){
            curChar = 0;
            try{
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    boolean isSpaceChar(int c)
    {
        return c==' '||c=='\n'||c=='\r'||c=='\t'||c==-1;
    }

    boolean isEndline(int c)
    {
        return c=='\n'||c=='\r'||c==-1;
    }

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

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

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

    String next(){
        int c = read();
        while (isSpaceChar(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do{
            res.appendCodePoint(c);
            c = read();
        }while(!isSpaceChar(c));
        return res.toString();
    }

    String nextLine(){
        int c = read();
        while (isEndline(c))
            c = read();
        StringBuilder res = new StringBuilder();
        do{
            res.appendCodePoint(c);
            c = read();
        }while(!isEndline(c));
        return res.toString();
    }
}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

public class Main {

  public static void main(String[] args) {
    // abc173_a();
    // abc173_b();
    // abc173_c();
    // abc172_a();
    // abc172_b();
    abc172_c();
  }

  // int 2147483648 [ 2 * 10(9)]
  // long 9223372036854775808 [ 9 * 10(18)]

  public static void abc172_a() {
    try (Scanner sc = new Scanner(System.in)) {
      int a = parseI(sc.next());

      System.out.println(a + (int) Math.pow(a, 2) + (int) Math.pow(a, 3));
    } catch (Exception e) {
      System.out.println("エラー" + e);
    }
  }

  public static void abc172_b() {
    try (Scanner sc = new Scanner(System.in)) {
      String s = sc.next();
      String t = sc.next();
      int ansCnt = 0;
      for (int i = 0; i < s.length(); i++) {
        if (!parseS(s.charAt(i)).equals(parseS(t.charAt(i)))) {
          ansCnt++;
        }
      }
      System.out.println(ansCnt);

    } catch (Exception e) {
      System.out.println("エラー" + e);
    }
  }

  public static void abc172_c() {
    try (Scanner sc = new Scanner(System.in)) {
      int n = parseI(sc.next());
      int m = parseI(sc.next());
      long k = parseL(sc.next());

      List<Integer> nList = new ArrayList<Integer>();
      List<Integer> mList = new ArrayList<Integer>();

      for (int i = 0; i < n; i++) {
        nList.add(parseI(sc.next()));
      }
      for (int i = 0; i < m; i++) {
        mList.add(parseI(sc.next()));
      }

      long sum = 0L;
      int ansCnt = 0;

      while (!nList.isEmpty() || !mList.isEmpty()) {
        if (mList.isEmpty()
          || !nList.isEmpty() && nList.get(0) < mList.get(0)) {
          sum += nList.get(0);
          if (k < sum) {
            break;
          }
          nList.remove(0);
          ansCnt++;
        } else {
          sum += mList.get(0);
          if (k < sum) {
            break;
          }
          mList.remove(0);
          ansCnt++;
        }
      }
      System.out.println(ansCnt);

    } catch (Exception e) {
      System.out.println("エラー" + e);
    }
  }

  public static void abc173_a() {
    try (Scanner sc = new Scanner(System.in)) {
      int payment = parseI(sc.next());
      int max = 10000;
      int thou = 1000;

      System.out.println((max - payment) % thou);
    } catch (Exception e) {
      System.out.println("エラー" + e);
    }
  }

  public static void abc173_b() {
    try (Scanner sc = new Scanner(System.in)) {
      int num = parseI(sc.next());

      // AC
      // WA
      // TLE
      // RE x 0
      int[] ansCount = new int[4];
      final String[] err = { "AC", "WA", "TLE", "RE" };
      Arrays.fill(ansCount, 0);

      for (int i = 0; i < num; i++) {
        String ans = sc.next();
        switch (ans) {
          case "AC":
            ansCount[0]++;
            break;
          case "WA":
            ansCount[1]++;
            break;
          case "TLE":
            ansCount[2]++;
            break;
          case "RE":
            ansCount[3]++;
            break;
        }
      }
      int count = 0;
      for (int answer : ansCount) {
        System.out.println(err[count] + " x " + answer);
        count++;
      }
    } catch (Exception e) {
      System.out.println("エラー" + e);
    }
  }

  public static void abc173_c() {
    try (Scanner sc = new Scanner(System.in)) {
      int row = parseI(sc.next());
      int column = parseI(sc.next());
      int checkBlackCount = parseI(sc.next());
      int existBlack = 0;
      int ansCount = 0;
      int[][] inputList = new int[row][column];
      String input = "";
      for (int i = 0; i < row; i++) {
        input = sc.next();
        for (int x = 0; x < column; x++) {
          inputList[i][x] =
            parseI(parseS(input.charAt(x)).replace(".", "0").replace("#", "1"));
        }
      }

      for (int i = 0; i < (1 << row); i++) {
        for (int x = 0; x < (1 << column); x++) {

          for (int chRownum = 0; chRownum < row; chRownum++) {
            for (int chColNum = 0; chColNum < column; chColNum++) {
              if (inputList[chRownum][chColNum] == 1
                && ((i >> chRownum) & 1) == 0 && ((x >> chColNum) & 1) == 0) {
                existBlack++;
              }
            }
          }
          if (existBlack == checkBlackCount) ansCount++;
          existBlack = 0;

        }
      }
      System.out.println(ansCount);

    } catch (Exception e) {
      System.out.println("エラー" + e);
    }
  }

  public static int parseI(String value) {
    return Integer.parseInt(value);
  }

  public static long parseL(String value) {
    return Long.parseLong(value);
  }

  public static double parseD(String value) {
    return Double.parseDouble(value);
  }

  public static <T> String parseS(T value) {
    return String.valueOf(value);
  }

}


import java.util.Scanner;

public class Main {
	public static void main(String[] args) {

		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int m = sc.nextInt();
		long k = sc.nextLong();
		long aSum[] = new long[n + 1];
		long bSum[] = new long[m + 1];
		int ans = 0;
		int max = n;
		for(int i = 1 ; i <= n ; i++) {
			aSum[i] = aSum[i - 1] + sc.nextLong();
		}

		for(int i = 0 ; i <= m ; i++) {
          if(i != m)
			bSum[i + 1] = bSum[i] + sc.nextLong();

			long best = k - bSum[i];
			if(best < 0)
				break;
			while(max > 0 && aSum[max] > best) max--;

			ans = Math.max(ans , i + max);
		}

		System.out.println(ans);

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;

public class Main {

    private static class FastReader {
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

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

    public static long[] buildPrefixArray(FastReader in, int n) {
        String[] tokens = in.nextLine().split(" ");
        long[] a = new long[n + 1];
        for (int i = 1; i <= n; i++) {
            a[i] = a[i - 1] + Long.parseLong(tokens[i - 1]);
        }
        return a;
    }

    public static void main(final String[] args) throws IOException {
        FastReader in = new FastReader();
        PrintWriter out = new PrintWriter(System.out, true);

        int n = in.nextInt();
        int m = in.nextInt();
        long k = in.nextInt();

        long[] a = buildPrefixArray(in, n);
        long[] b = buildPrefixArray(in, m);

        int books = 0;
        for (int i = 1; i <= n; i++) {
            if (a[i] > k) {
                break;
            }
            for (int j = m; j >= 1; j--) {
                if (b[j] <= k - a[i]) {
                    books = Math.max(books, i + j);
                    break;
                }
            }
        }
        out.println(books);
    }
}


import java.util.Scanner;

public class Main {

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

			final int n = sc.nextInt();
			final int m = sc.nextInt();
			int k = sc.nextInt();

			final Integer[] n_b = new Integer[n];
			for (int i = 0; i < n; i++) {
				n_b[i] = sc.nextInt();
			}

			final Integer[] m_b = new Integer[m];
			for (int i = 0; i < m; i++) {
				m_b[i] = sc.nextInt();
			}

			int count=0;

			int offset_n=0;
			int offset_m=0;

			while(k!=0) {

				final Integer nBook = getBook(n_b, offset_n);
				final Integer mBook = getBook(m_b, offset_m);

				final int t;
				if(nBook==null&&mBook==null) {
					break;

				}else if(nBook==null) {
					t=mBook;
					offset_m++;

				}else if(mBook==null) {
					t=nBook;
					offset_n++;

				}else {

					if(nBook <= mBook) {
						t = nBook;
						offset_n++;

					}else {
						t=mBook;
						offset_m++;
					}
				}

				if(k < t) {
					break;
				}

				count++;
				k-=t;
			}

			System.out.println(count);
		}
	}

		private static Integer getBook(final Integer[] books, final int offset) {
			if(books.length == offset) {
				return null;
			}
			return books[offset];
		}

}


import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        // Your code here!
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        int K = sc.nextInt();

        double A[] = new double[N];
        double B[] = new double[M];

        int count = 0;
        double time = 0;
        int a = 0;
        int b = 0;

        for(int i=0;i<N;i++){
            A[i] = sc.nextDouble();
        }

        for(int i=0;i<M;i++){
            B[i] = sc.nextDouble();
        }

        while(time<=K){
            if(A[a]<B[b]){
                time += A[a];
                a++;
                count++;
            } else {
                time += B[b];
                b++;
                count++;
            }
        }

        if(time>K){
            count--;
        }

        System.out.println(count);
    }
}


import java.io.*;
import java.util.*;
public class Main {
    static long startTime;
    static long endTime;
    static Boolean [] prime ;
    static Scanner sc = new Scanner(System.in);
    static class FastReader{
        BufferedReader br;
        StringTokenizer st;

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

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

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

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

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

        String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
    }
    public static int lowerBound
            (Integer[] array, int length, int value) {
        int l = 0;
        int r = length;
        while (l < r) {
            int mid = (l + r) / 2;
            if (value < array[mid]) {
                r = mid;
            } else {
                l = mid + 1;
            }
        }
        return l;
    }
    public static long gcd(long a, long b){
        if (b == 0)
            return a;
        else return gcd(b, a % b);
    }
    public  static  long countDivs(long n ){
        int cn=0;
        long sqr = (long)Math.sqrt(n);
        for (long i = 1; i<=sqr ; ++i) {
            if(n%i==0){
                ++cn;
            }
        }
        cn*=2;
        if(sqr*sqr==n) cn--;
        return cn;

    }
    static void prime(int  x) {
        //sieve algorithm. nlog(log(n)).
        prime=new Boolean[ (x+1)];
        Arrays.fill(prime,true);
        prime[0] = prime[1] = false;
        for (int  i = 2; i * i <= x ; i++)
            if (prime[i])
                for (int  j = i * i; j <= x; j += i)
                    prime[j] = false;
    }
    static int[] sum;
    static void cumulitiveSum( int [] arr){
        sum = new int[arr.length];
        sum[0]=arr[0];
        for (int i = 1; i <arr.length; i++) {
            sum[i]=arr[i]+sum[i-1];
        }
    }
    public static void main(String [] args)  {
        startTime = System.currentTimeMillis();
       // int T = sc.nextInt();while (T--!=0)
        {
            solve();
        }
        endTime = System.currentTimeMillis();
        long duration= endTime-startTime;
        //System.out.println(duration);
    }
    public static void solve()  {
//////////////////////////////////////////////////////////////////////
        int n =sc.nextInt();
        int m =sc.nextInt();
        int k =sc.nextInt();
        Deque<Integer> a = new LinkedList<>();
        Deque<Integer>  b = new LinkedList<>();

        // Integer [] a = new Integer [n];
        //Integer [] b = new Integer[m];
        for (int i = 0; i < n; i++) {
            a.add(sc.nextInt());
        }
        for (int i = 0; i < m; i++) {
            b.add(sc.nextInt());
        }

        long cn=0;
        long sum=0;
        int j=0;
        while(sum<k){
            if(b.isEmpty()&&a.isEmpty()) {
                break;
            }
            if( b.isEmpty() || (!a.isEmpty() &&  a.getFirst()<=b.getFirst())){
                sum+=a.getFirst();
                a.removeFirst();
            }
            else {
                sum += b.getFirst();
                b.removeFirst();
            }

            cn++;

        }
        if(sum==k){
            System.out.println(cn);
        }
        else System.out.println(cn-1);
///////////////////////////////////////////////////////////////////////
    }

}


import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

public class Main {
  public static void main(String[] args){
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int m = sc.nextInt();
    BigInteger k = new BigInteger(sc.next());
    ArrayList<BigInteger> a = new ArrayList<>();
    ArrayList<BigInteger> b = new ArrayList<>();

    int indexA = -1;
    int indexB = -1;
    BigInteger sum = BigInteger.ZERO;
    boolean boo = true;
    for (int i = 0; i < n; i++) {
      BigInteger aTmp = new BigInteger(sc.next());
      BigInteger tmp = sum.add(aTmp);
      if (boo && tmp.compareTo(k) <= 0) {
        indexA = i;
        sum = tmp;
      } else {
        boo = false;
      }
      a.add(aTmp);
    }
    boo = sum.compareTo(k) <= 0;
    for (int i = 0; i < m; i++) {
      BigInteger bTmp = new BigInteger(sc.next());
      BigInteger tmp = sum.add(bTmp);
      if (boo && tmp.compareTo(k) <= 0) {
        indexB = i;
        sum = tmp;
      } else {
        boo = false;
      }
      b.add(bTmp);
    }

    int max = (indexA + 1) + (indexB + 1);
    for (int i = indexA; i >= 0; i--) {
      if (indexB == m - 1) {
        break;
      }
      sum = sum.subtract(a.get(i));
      BigInteger tmp = sum;
      while (true) {
        if (indexB == m - 1) {
          break;
        }
        tmp = tmp.add(b.get(indexB + 1));
        if (tmp.compareTo(k) <= 0) {
          indexB++;
          sum = tmp;
        } else {
          break;
        }
      }
      int t = i + (indexB + 1);
      if (t > max) {
        max = t;
      }
    }
    System.out.println(max);
  }

}


import java.util.Scanner;

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

		int[] a = new int[sc.nextInt()];
		int[] b = new int[sc.nextInt()];
		int k = sc.nextInt();

		for (int i = 0; i < a.length; i++) {
			a[i] = sc.nextInt();
		}
		for (int i = 0; i < b.length; i++) {
			b[i] = sc.nextInt();
		}
		sc.close();

		long sum = 0L;
		int markA = 0;
		int markB = 0;
		while (sum < k) {
			if (markA < a.length && markB < b.length) {
				if (a[markA] < b[markB]) {
					if (sum + a[markA] > k)
						break;
					sum += a[markA];
					markA++;
				} else {
					if (sum + b[markB] > k)
						break;
					sum += b[markB];
					markB++;
				}
			} else if (markA < a.length) {
				if (sum + a[markA] > k)
					break;
				sum += a[markA];
				markA++;
			} else if (markB < b.length) {
				if (sum + b[markB] > k)
					break;
				sum += b[markB];
				markB++;
			}

		}
		System.out.println(markA + markB);
	}
}