import Foundation

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

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

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

var input: [Int] = []
for _ in 0..<5 {
    input.append(readInt()!)
}
var sum = 0
var overTime: [Int] = []
for i in input {
    let time = (i + 9) / 10 * 10
    sum += time
    overTime.append(time - i)
}
print(sum - overTime.max()!)


var array: [Int] = []
var sum = 0

for _ in 0..<5 {
  let item = Int(readLine()!)!
  let a = item % 10
  sum += (item - a)
  if a != 0 {
    array.append(a)
  }
}

if array.count == 0 {
  print(sum)
} else {
  array.sortInPlace { (lhs, rhs) in
    return a > b
  }
  for i in 0..<array.count-1 {
    let item = array[i]
    let amari = item % 10
    let add = item + 10 - amari
    sum += add
  }
  sum += array[array.count-1]
  print(sum)
}


var array1: [Int] = []
var array2 : [Int] = []

for _ in 0..<5 {
  let line = readLine()!
  let item = Int(line)!
  if item % 10 == 0 {
    array1.append(item)
  } else {
    array2.append(item)
  }
}

array2.sortInPlace { (lhs, rhs) in
  let a = lhs % 10
  let b = rhs % 10
  return a > b
}

var sum = 0
for i in 0..<array1.count {
  let item = array1[i]
  sum += item
}

for i in 0..<array2.count-1 {
  let item = array2[i]
  let amari = item % 10
  let add = item + 10 - amari
  sum += add
}
sum += array2[array2.count-1]

print(sum)


var array1: [Int] = []
var array2 : [Int] = []

for _ in 0..<5 {
  let line = readLine()!
  let item = Int(line)!
  if item % 10 == 0 {
    array1.append(item)
  } else {
    array2.append(item)
  }
}

array2.sortInPlace { (lhs, rhs) in
  let a = lhs % 10
  let b = rhs % 10
  return a > b
}

var sum = 0
for i in 0..<array1.count {
  let item = array1[i]
  sum += item
}

for i in 0..<array2.count-1 {
  let item = array2[i]
  let amari = item % 10
  let add = item + 10 - amari
  sum += add
}
sum += array2[array2.count]

print(sum)


export class Main {
  static main(input): string {
    const tmp: number[] = input.split("\n").map(s => Number(s.split(" ")[0]));
    let index: number = 0;
    let minR: number = Infinity;
    for (let i = 0; i < 5; i++) {
      const r: number = tmp[i] % 10;
      if (0 < r && r < minR) {
        minR = r;
        index = i;
      }
    }
    let result: number = tmp[index];
    for (let i = 0; i < 5; i++) {
      if (i != index) {
        const r: number = tmp[i] % 10;
        result += tmp[i] - r + (r === 0 ? 0 : 10);
      }
    }
    return `${result}`;
  }
}
console.log(Main.main(require("fs").readFileSync("/dev/stdin", "utf8")));


const main = (input) => {
  const lines = input.split("\n").map(str => parseInt(str));
  let sum = 0;
  let maxLoss = 0;
  lines.forEach(time => {
    virtualTime = Math.ceil(time / 10) * 10;
    sum += virtualTime
    maxLoss = Math.max(maxLoss, virtualTime - time);
  });
  console.log(sum - maxLoss);
};

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


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

const menu = stdin.split('\n').map(Number)

const lastEl = getBiggest(menu)

const index = menu.indexOf(lastEl)

menu.splice(index, 1)

const res = menu.map(el => {
  if (el % 10 === 0) return el
  return el + 10 - (el % 10)
})
.reduce((acc, curr) => {
  return acc + curr
})

console.log(res+lastEl)

function getBiggest(nums) {
  let el = 0
  const biggest = nums.reduce((acc, c) => {
    const remain = 10 - (c % 10)
    if (remain === 10) return acc
    if (remain > acc) {
      el = c
      return remain
    }
    return acc
  }, 0)
  return el
}


import * as fs from 'fs';

const main = (input: string) => {
  const lines = input.split("\n").map(str => parseInt(str));
  let sum = 0;
  let maxTime = 0;
  let w: number[] = [];

  lines.forEach((time) => {
    if (time % 10 !== 0) {
      w.push(10 - time % 10)
    }

    sum += (Math.ceil(time / 10) * 10)
  });

  if (w !== []) {
    maxTime = w.reduce((a, b) => Math.max(a, b))
  }

  console.log(sum - maxTime);
};

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


import * as fs from 'fs';

const main = (input: string) => {
  const lines = input.split("\n").map(str => parseInt(str));
  let sum = 0;
  let maxTime = 0;
  let w: number[] = [];

  lines.forEach((time) => {
    if (time % 10 !== 0) {
      w.push(10 - time % 10)
    }

    sum += (Math.ceil(time / 10) * 10)
  });

  maxTime = w.reduce((a, b) => Math.max(a, b))

  console.log(sum - maxTime);
};

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


import * as fs from 'fs';

const main = (input: string) => {
  const lines = input.split("\n").map(str => parseInt(str));
  let answer = 0;
  let maxTime;
  let w: number[] = [];

  lines.forEach((time) => {
    if (time % 10 !== 0) {
      w.push(10 - time % 10)
    }

    answer += (Math.ceil(time / 10) * 10)
  });

  maxTime = w.reduce((a, b) => Math.max(a, b))

  console.log(answer - maxTime);
};

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


n,k = map(int, input().split())

if n%k==0:
    print("0")
else:
    print("1")


N,K = map(int,input().split())
if N % K == 0:
  print(0)
else:
  print(1)


a,b=map(int,input().split())
if a%b==0:print(0)
else:print(1)


N,K = map(int, input().split())

print(N//K+(N%K)-N//K)


a,b = map(int,input().split())
n = a / b
div = a % b
print(div)


import re, math

def mapt(fn, *args):
    return list(map(fn, *args))

def Input():
    return mapt(int, input().split(" "))

def main():
    n, k = Input()
    if n % k == 0:
        print(0)
    else:
        max_n = math.ceil(k/n)
        min_n = math.floor(k/n)
        print(max_n - min_n)

main()


import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.NoSuchElementException;

public class Main {
    public static void main(String[] args) {
        FastScanner sc = new FastScanner();
        int n = sc.nextInt();
        int k = sc.nextInt();
        if (n%k == 0) {
            System.out.println(0);
        } else {
            System.out.println(1);
        }
    }
}

class FastScanner {
    public static String debug = null;

    private final InputStream in = System.in;
    private int ptr = 0;
    private int buflen = 0;
    private byte[] buffer = new byte[1024];
    private boolean eos = false;

    private boolean hasNextByte() {
        if (ptr < buflen) {
            return true;
        } else {
            ptr = 0;
            try {
                if (debug != null) {
                    buflen = debug.length();
                    buffer = debug.getBytes();
                    debug = "";
                    eos = true;
                } else {
                    buflen = in.read(buffer);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (buflen < 0) {
                eos = true;
                return false;
            } else if (buflen == 0) {
                return false;
            }
        }
        return true;
    }

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

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

    private void skipUnprintable() {
        while (hasNextByte() && !isPrintableChar(buffer[ptr]))
            ptr++;
    }

    public boolean isEOS() {
        return this.eos;
    }

    public boolean hasNext() {
        skipUnprintable();
        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() {
        return (int) nextLong();
    }

    public long[] nextLongList(int n) {
        return nextLongTable(1, n)[0];
    }

    public int[] nextIntList(int n) {
        return nextIntTable(1, n)[0];
    }

    public long[][] nextLongTable(int n, int m) {
        long[][] ret = new long[n][m];
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                ret[i][j] = nextLong();
            }
        }
        return ret;
    }

    public int[][] nextIntTable(int n, int m) {
        int[][] ret = new int[n][m];
        for (int i = 0; i < n; i ++) {
            for (int j = 0; j < m; j ++) {
                ret[i][j] = nextInt();
            }
        }
        return ret;
    }
}


import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

public class Main {

	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		long N = sc.nextLong();
		long K = sc.nextLong();

		System.out.println(N % K == 0 ? 0 : 1);
	}

	private static boolean isDebug = System.getProperty("sun.desktop") != null;

	private static void debug(Object... o) {
		if (isDebug) {
			System.err.println(Arrays.deepToString(o));
		}
	}

	public static class Scanner {
		private BufferedInputStream inputStream;
		private StringBuilder buffer = new StringBuilder();

		public Scanner(InputStream in) {
			inputStream = new BufferedInputStream(in);
		}

		public int nextInt() throws IOException {
			int num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(int[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextInt();
			}
		}

		public void fill(int[] a, int[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

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

		public long nextLong() throws IOException {
			long num = 0;
			int sign = 1;

			int read = skip();
			if (read == '-') {
				sign = -1;
				read = inputStream.read();
			}

			do {
				num = num * 10 + sign * (read - 0x30);
			} while ((read = inputStream.read()) > 0x20);

			return num;
		}

		public void fill(long[] a) throws IOException {
			for (int i = 0; i < a.length; i++) {
				a[i] = nextLong();
			}
		}

		public void fill(long[] a, long[] b) throws IOException {
			if (a.length != b.length) {
				throw new IllegalArgumentException();
			}

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

		public long[] nextLong(int n) throws IOException {
			long[] array = new long[n];
			for (int i = 0; i < n; i++) {
				array[i] = nextLong();
			}

			return array;
		}

		public String next() throws IOException {
			int read = skip();
			do {
				buffer.append((char) read);
			} while ((read = inputStream.read()) > 0x20);

			String text = buffer.toString();
			buffer.delete(0, buffer.length());

			return text;
		}

		private int skip() throws IOException {
			int read;
			while ((read = inputStream.read()) <= 0x20)
				;

			return read;
		}
	}
}


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

public class Main {

	final static long MOD = 1000000007;
	public static String[] Ws = null;
	public static int wsIndx = 0;
	public static BufferedReader in = null;
	public static void main(String[] args) throws Exception {
		solution(args);
		if(in!=null){
			in.close();
		}
	}

	public static void solution(String[] args) throws Exception{

		int N = nextInt();
		int K = nextInt();

		System.out.println(N%K!=0?1:0);

	}
	public static String[] toStringArray(String s) {
		String[] tmp = new String[s.length()];
		char[] c = s.toCharArray();
		for (int i = 0; i < tmp.length; i++) {
			tmp[i] = String.valueOf(c[i]);
		}
		return tmp;
	}

	public static void check() throws Exception{
		if(in == null){
			in = new BufferedReader(new InputStreamReader(System.in));
		}
		if(Ws==null || Ws.length<=wsIndx){
			Ws = in.readLine().split(" ");
			wsIndx=0;
		}
	}
	public static int nextInt()throws Exception{
		check();
		return Integer.parseInt(Ws[wsIndx++]);
	}

	public static long nextLong()throws Exception{
		check();
		return Long.parseLong(Ws[wsIndx++]);
	}

	public static String nextString()throws Exception{
		check();
		return Ws[wsIndx++];
	}

	public static int[] nextInts()throws Exception{
		check();
		int[] tmp = new int[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Integer.parseInt(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static long[] nextLongs()throws Exception{
		check();
		long[] tmp = new long[Ws.length];
		for(int i=0;i<tmp.length;i++){
			tmp[i]=Long.parseLong(Ws[i]);
		}
		wsIndx=Ws.length;
		return tmp;
	}

	public static String[] nextStrings()throws Exception{
		check();
		wsIndx=Ws.length;
		return Ws;
	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		new Solution();
	}

}

class Solution {

	private int n, k;

	public Solution() {
		this.setScanner();
		this.run();
	}

	private void setScanner() {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		sc.close();
	}

	private void run() {
		int min = n / k;
		int max = n / k + n % k;
		int out = (max != min) ? max - min : 0;
		System.out.println(out);
	}

}


import java.util.Scanner;

public class Main {

	public static void main(String[] args) {

		new Solution();

	}

}

class Solution {

	private int n, k;

	public Solution() {
		this.setScanner();
		this.run();
	}

	private void setScanner() {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		k = sc.nextInt();
		sc.close();
	}

	private void run() {
		int max = n / k;
		int min = n % k;
		int out = (min != 0) ? max - min : 0;
		System.out.println(out);
	}

}


mport java.util.Scanner;

public class Main {
	public static void main(String[] args) throws Exception {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		int k = sc.nextInt();
		sc.close();

		System.out.println(n % k == 0 ? 0 : 1);
	}
}


#include<stdio.h>

int main(void){
  int N,K;
  scanf("%d",&N);
  scanf("%d",&K);
  if(N%K==0){
    printf("0");
  }
  else{
    printf("1");
  }
  return 0;
}


#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#include<algorithm>
using namespace std;
#define fo(i,a,b) for(int i=a;i<=b;i++)
#define fd(i,a,b) for(int i=a;i>=b;i--)
int a,b;
int main(){
	scanf("%d%d",&a,&b);
	if (a%b) printf("1\n");else printf("0\n");
	return 0;
}


#include <stdio.h>
int main(){
  int a,b;
  scanf("%d %d",&a,&b);
  printf("%d\n",(a%b==0)?0:1);
  return 0;
}


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
#define chmax(x,y) x = max(x,y);
#define chmin(x,y) x = min(x,y);
const int di[] = {-1, 0, 1, 0};
const int dj[] = {0, -1, 0, 1};
const int INF = 1001001001;

int main() {
    int n, k;
    cin >> n >> k;
    if (n%k == 1) cout << 1 << endl;
    else cout << 0 << endl;
    return 0;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <iomanip>
#include <algorithm>
#include <sstream>
#include <string>
#include <math.h>
#include <set>
#include <deque>
#include <queue>
#include <list>
using namespace std;
typedef long long ll;
const int mod = 1000000007;

#define for1(n) for (int i = 0 ; i < n ; i++)
#define for2(n) for (int j = 0 ; j < n ; j++)
#define for1l(n) for (ll i = 0 ; i < n ; i++)
#define for2l(n) for (ll j = 0 ; j < n ; j++)

int main() {
    ios::sync_with_stdio(false);
    int n, k;
    cin >> n >> k;
    if (a % b == 0) cout << 0;
    else cout << 1;
}


#include <iostream>
#include <cmath>
#include <vector>
#include <map>
#include <iomanip>
#include <algorithm>
#include <sstream>
#include <string>
#include <math.h>
#include <set>
#include <deque>
#include <queue>
#include <list>
using namespace std;
typedef long long ll;
const int mod = 1000000007;

#define for1(n) for (int i = 0 ; i < n ; i++)
#define for2(n) for (int j = 0 ; j < n ; j++)
#define for1l(n) for (ll i = 0 ; i < n ; i++)
#define for2l(n) for (ll j = 0 ; j < n ; j++)

int main() {
    ios::sync_with_stdio(false);
    int n, k;
    cin >> n >> k;
    cout << n % k;
}


#include <stdio.h>

int main(){
  int n, k;

  scanf( "%d", &n );
  scanf( "%d", &k );

  if ( n % k == 0 ){
    puts( "0" );
  }else {
    puts( "1" );
  }

  return 0;
}


#include <stdio.h>
int main(){
  int n,k;
  scanf("%d %d",&n,&k );
  if(n%k==0)
  printf("0\n");
  else
  printf("1\n");
}


#include<stdio.h>
#include <string.h>
int main()
{
	int n,k,a,b;
	scanf("%d%d",&n,&k);
	a=n%k;
	if(a>0){
		b=1;
		printf("%d\n",b);
	}
	else {
		b=0;
		printf("%d\n",b);
	}
	return 0;
}


#include<stdio.h>
int main(void)
{
	int n,k,x;
	scanf("%d %d",&n,&k);
		x=n%k;
		printf("%d\n",x);
	return 0;
}


#include<stdio.h>
int main(){
  int a,b;
  scanf("%d",&a,&b);
  printf("%d",a%b?1:0);
}


#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
#include <stdbool.h>

#define rep(i, n) for(int i=0; i<(n); ++i)
#define max  200001

//qsort(str, n, sizeof(int), up_comp);
int up_comp(const void *a, const void *b){return *(int*)a - *(int*)b;}
int down_comp(const void *a, const void *b){return *(int*)b - *(int*)a;}
int int_sort( const void * a , const void * b ) {return strcmp(( char * )a , ( char * )b );}
int count_digit(int a){int i=0;while(a!=0){a=a/10;i++;}return i;}
int euclid( int a, int b ){int temp;if(a<b){temp=a;a=b;b=temp;}if(b<1)return -1;if(a%b==0) return b;return euclid(b,a%b);}

int main(void){

    int n, k;

    scanf("%d%d", &n, &k);

    printf("%d", n%k);

    return 0;
}


function Main(input) {
  // 1行目がinput[0], 2行目がinput[1], …に入る
  var splitInput = input.split(" ");

  var a = parseInt(splitInput[0], 10);
  var b = parseInt(splitInput[1], 10);

  if (a % b) {
    console.log(1);
  } else {
    console.log(0);
  }
}

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


const main = function(input){
  var nums = input.trim().split(" ").map(i=>parseInt(i));
  var n = nums[0];
  var k = nums[1];
  var ans = 1;

  if(k<=n && n%k ===0){
  	ans = 0;
  }

  console.log(ans);

}

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


function main(input) {
  const n = parseInt(input.split(" ")[0], 10);
  const k= parseInt(input.split(" ")[1], 10);
  if(n%k==0){
    console.log(0);
  }else{
    console.log(1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const args = input.split(' ');
  const N = args[0];
  const K = args[1];

  if (N % K === 0) {
    console.log(0);
  } else {
    console.log(Math.floor(N % K));
  }
}

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


function main(input){
  var int = Number.parseInt(input);
  var sum = 0;
  var result = 'No';

  CakeDonut:
  for(let i=0;sum<int;i++){
    for(let j=0;sum<int;j++){
      sum = 4*i+7+j;
      if(sum === int){
        result = 'Yes';
        break CakeDonut;
      }
    }
  }
  console.log(result);
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function main(input) {
  const n = parseInt(input.split(" ")[0], 10);
  const k= parseInt(input.split(" ")[1], 10);
  if(N%K==0){
    console.log(0);
  }else{
    console.log(1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


package main

import (
    . "fmt"
)

func main() {
    var n, k int
    Scanf("%d %d", &n, &k)

    if n % k == 0 {
        Println(0)
    } else {
        Println(1)
    }
}


package main
import "fmt"
func main(){
    var n, k int
    fmt.Scan(&n, &k)

    if n%k == 0{
        fmt.Println(0)
    }else{
        fmt.Println(1)
    }
}


package main

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

func main() {
	sc.Split(bufio.ScanWords)
	n, k := nextInt(), nextInt()
	puts((n-1+k)/k - n/k)
	wt.Flush()
}

var (
	sc  = bufio.NewScanner(os.Stdin)
	rdr = bufio.NewReaderSize(os.Stdin, 1000000)
	wt  = bufio.NewWriter(os.Stdout)
)

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

func nextInt() int {
	i, _ := strconv.Atoi(next())
	return i
}

func nextFloat64() float64 {
	f, _ := strconv.ParseFloat(next(), 64)
	return f
}

func nextInts(n int) []int {
	slice := make([]int, n)
	for i := 0; i < n; i++ {
		slice[i] = nextInt()
	}
	return slice
}

func nextFloat64s(n int) []float64 {
	slice := make([]float64, n)
	for i := 0; i < n; i++ {
		slice[i] = nextFloat64()
	}
	return slice
}

func nextMega() string {
	buf := make([]byte, 0, 1000000)
	for {
		l, p, _ := rdr.ReadLine()
		buf = append(buf, l...)
		if !p {
			break
		}
	}
	return string(buf)
}

func putf(format string, a ...interface{}) {
	fmt.Fprintf(wt, format, a...)
}

func puts(a ...interface{}) {
	fmt.Fprintln(wt, a...)
}


package main

import (
	"bufio"
	"fmt"
	//"math"
	"os"
	"strconv"
	"strings"
)

func main() {
	r := bufio.NewReader(os.Stdin)
	s, _ := r.ReadString('\n')
	s = strings.TrimRight(s, " \t\n")
	slice := strings.Split(s, " ")
	n := string(slice[0])
	k := string(slice[1])
	N, _ := strconv.Atoi(n)
	K, _ := strconv.Atoi(k)

	fmt.Println(N % K)
}


package main

import "fmt"

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

	if n%k == 0 || n/k == 0 {
		fmt.Println(0)
	} else {
		fmt.Println(n%k)
	}
}


package main

import "fmt"

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

	if n%k == 0 {
		fmt.Println(0)
	} else {
		fmt.Println(n%k)
	}
}


# abc105 A
n, k = gets.split.map(&:to_i)
p (n == k || n % k == 0) ? 0 : 1


n, k = gets.chomp.split.map(&:to_i)
puts (n % k != 0)? "1" : "0"


input = gets.chomp.split
n = input[0].to_i
k = input[1].to_i
puts n % k == 0 ? 0 : 1


a,b=gets.split.map(&:to_i)
p a%b==0?0:a-b*(a/b)


a,b=gets.split.map(&:to_i)
p a%b==0?0:a-b.*a/b


puts gets.split.map(&:to_i).inject(:%)==0?$_.split.map(&:to_i).inject(:%):$_.split[0].to_i/$_.split[1].to_i-$_.split.map(&:to_i).inject(:%)


#[allow(unused_macros, dead_code)]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        let mut next = || { iter.next().unwrap() };
        input_inner!{next, $($r)*}
    };
    ($($r:tt)*) => {
        let stdin = std::io::stdin();
        let mut bytes = std::io::Read::bytes(std::io::BufReader::new(stdin.lock()));
        let mut next = move || -> String{
            bytes
                .by_ref()
                .map(|r|r.unwrap() as char)
                .skip_while(|c|c.is_whitespace())
                .take_while(|c|!c.is_whitespace())
                .collect()
        };
        input_inner!{next, $($r)*}
    };
}

#[allow(unused_macros, dead_code)]
macro_rules! input_inner {
    ($next:expr) => {};
    ($next:expr, ) => {};

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

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

#[allow(unused_macros, dead_code)]
macro_rules! read_value {
    ($next:expr, ( $($t:tt),* )) => {
        ( $(read_value!($next, $t)),* )
    };

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

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

    ($next:expr, bytes) => {
        read_value!($next, String).into_bytes()
    };

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

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

#[allow(dead_code)]
struct UnionFind {
    parent: Vec<usize>,
    rank: Vec<usize>,
    size: Vec<usize>,
}

#[allow(dead_code)]
impl UnionFind {
    fn new(n: usize) -> UnionFind {
        let mut p = vec![0; n];
        for i in 0..n {
            p[i] = i;
        }
        return UnionFind {
            parent: p,
            rank: vec![0; n],
            size: vec![1; n],
        };
    }

    fn find(&mut self, x: usize) -> usize {
        if x == self.parent[x] {
            x
        } else {
            let p = self.parent[x];
            let pr = self.find(p);
            self.parent[x] = pr;
            pr
        }
    }

    fn same(&mut self, a: usize, b: usize) -> bool {
        self.find(a) == self.find(b)
    }

    fn unite(&mut self, a: usize, b: usize) {
        let a_root = self.find(a);
        let b_root = self.find(b);
        if a_root == b_root {
            return;
        }
        if self.rank[a_root] > self.rank[b_root] {
            self.parent[b_root] = a_root;
            self.size[a_root] += self.size[b_root];
        } else {
            self.parent[a_root] = b_root;
            self.size[b_root] += self.size[a_root];
            if self.rank[a_root] == self.rank[b_root] {
                self.rank[b_root] += 1;
            }
        }
    }

    fn get_size(&mut self, x: usize) -> usize {
        let root = self.find(x);
        self.size[root]
    }
}

const MOD_P: usize = 1000000007;

#[allow(dead_code)]
// fact(n) = n! mod p
fn fact(n: usize) -> usize {
    let mut acc = 1;
    for i in 1..n + 1 {
        acc = acc * i % MOD_P;
    }
    acc
}

#[allow(dead_code)]
fn mod_pow(b: usize, mut e: usize) -> usize {
    let mut base = b;
    let mut acc = 1;

    while e > 1 {
        if e % 2 == 1 {
            acc = acc * base % MOD_P;
        }
        e /= 2;
        base = base * base % MOD_P;
    }

    if e == 1 {
        acc = acc * base % MOD_P;
    }

    acc
}

#[allow(dead_code)]
fn comb(n: usize, r: usize) -> usize {
    // nCr = n! / (r! (n-r)!) = n! (r!)^(p-2) ((n-r)!)^(p-2)
    let x = ((n - r + 1)..(n + 1)).fold(1, |p, x| p * x % MOD_P);
    let y = mod_pow(fact(r), MOD_P - 2);
    x * y % MOD_P
}

#[allow(dead_code)]
fn gcd(a: usize, b: usize) -> usize {
    if b > a {
        gcd(b, a)
    } else if a % b == 0 {
        b
    } else {
        gcd(b, a % b)
    }
}

#[allow(dead_code)]
fn getline() -> String {
    let mut __ret = String::new();
    std::io::stdin().read_line(&mut __ret).ok();
    return __ret;
}

use std::cmp::{max, min};

fn main() {
    input! {
        n: usize,
        k: usize,
    }
    let ans = if n % k == 0 { 0 } else { 1 };
    println!("{}", ans);
}


use std::io::*;
use std::str::FromStr;

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

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

    println!("{}", (n % k != 0) as u32);
}


use std::io;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let v:Vec<i32> = procon_read();
	let n = v[0];
	let k = v[1];
	if n%k != 0 {
		println!("1");
	}else{
		println!("0");
	}
}


use std::io::*;
use std::str::FromStr;

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

use std::collections::HashMap;

fn main() {
    let n: usize = read();
    let m: i64 = read();
    let mut a: Vec<i64> = vec![];

    for _ in 0..n {
        a.push(read());
    }

    let mut sum = 0;
    let mut ans = 0;
    let mut b: HashMap<i64, i64> = HashMap::new();
    b.insert(0, 1);
    let mut c: Vec<i64> = vec![];
    for i in 0..a.len() {
        sum += a[i];
        match b.get(&(sum % m)) {
            Some(s) => ans += *s,
            None => (),
        }
        let current = b.entry((sum % m)).or_insert(0);
        *current += 1;
    }
    println!("{}", ans);
}


use std::io;

fn procon_read<T: std::str::FromStr>() ->  Vec<T> {
	let mut buf = String::new();
	io::stdin().read_line(&mut buf).expect("");
	let iter = buf.split_whitespace();
	let mut v: Vec<T> = Vec::new();
	for i in iter {
		v.push(i.parse().ok().unwrap());
	}
	v
}

fn main() {
	let v:Vec<i32> = procon_read();
	let n = v[0];
	let k = v[1];
	if n%k != 0 {
		println!("{}", (n/k - n%k).abs());
	}else{
		println!("0");
	}
}


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

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

macro_rules! read_value {
    ($iter:expr, ( $($t:tt),* )) => {
        ( $(read_value!($iter, $t)),* )
    };
    ($iter:expr, [ $t:tt ; $len:expr ]) => {
        (0..$len).map(|_| read_value!($iter, $t)).collect::<Vec<_>>()
    };
    ($iter:expr, chars) => {
        read_value!($iter, String).chars().collect::<Vec<char>>()
    };
    ($iter:expr, usize1) => {
        read_value!($iter, usize) - 1
    };
    ($iter:expr, $t:ty) => {
        $iter.next().unwrap().parse::<$t>().expect("Parse error")
    };
}

fn main() {
    input! {
        n: i32,
        k: i32
    }
    let m = n % k;
    if m == 0 {
        println!("0");
    } else {
        println!("{}", m);
    }
}


let i=readLine()!.characters.split(" ").map{Int(String($0))!};print(i[0]%i[1]>0 ?1:0)


//let i=readLine()!.characters.split(" ").map{Int(String($0))!};print(i[0]%i[1]>0 ?1:0)
print(readLine()!.characters.split(" ").map{Int(String($0))!}.reduce(1){$0%$1}>0 ?1:0)


//let i=readLine()!.characters.split(" ").map{Int(String($0))!};print(i[0]%i[1]>0 ?1:0)
print(readLine()!.characters.split(" ").map{Int(String($0))!}.reduce(0){$0%$1}>0 ?1:0)


let i=readLine()!.characters.split(" ").map{Int(String($0))!};print(i[0]%i[1] ?1:0)


const main = (input) => {
  input = input.split(' ');
  const n = parseInt(input[0], 10);
  const k = parseInt(input[1], 10);

  if(n%k==0){
    console.log(0);
  }else{
    console.log(1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


function Main(input){
	var args = input.split(' ');
	var N = parseInt(args[0],10);
  	var K = parseInt(args[1],10);
if(N%K===0){
  console.log('0');
}else{
 console.log('1');
}

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


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


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


const main = (input) => {
  input = input.split(' ');
  const n = parseInt(input[0], 10);
  const k = parseInt(input[1], 10);

  if)(n%k==0){
    console.log(0);
  }else{
    console.log(1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


const main = (input) => {
  input = input.split(' ');
  const n = parseInt(input[0], 10);
  const k = parseInt(input[1], 10);

  if)(n%k===0){
    console.log(0);
  }else{
    console.log(1);
  }
}
main(require('fs').readFileSync('/dev/stdin', 'utf8'));


from sys import stdin
input = stdin.buffer.readline

def main():
    n, w = map(int, input().split())
    wv = [tuple(map(int, input().split())) for _ in range(n)]

    sum_v = sum([value for weight, value in wv])
    dp = [w + 1] * (sum_v + 1)
    dp[0] = 0
    for weight, value in wv:
        for i in range(sum_v - value + 1)[::-1]:
            if dp[i + value] > dp[i] + weight:
                dp[i + value] = dp[i] + weight

    for i in range(sum_v + 1)[::-1]:
        if dp[i] <= w:
            print(i)
            break

main()


N, W = map(int, input().split())
ITEM = []
vmax, wmax = 0,0
for _ in range(N):
  w,v = map(int, input().split())
  ITEM.append((v,w))
  vmax = max(vmax,v)
  wmax = max(wmax,w)

INF = 10**18

def solve1():
  #dp[i][v] i個めまで選んで、価値Vを実現するための最小の重量
  # TLEしたらiを消す。
  dp = [INF] * (vmax*N+1)
  dp[0] = 0
  for i in range(1,N+1):
    v1,w1 = ITEM[i-1]
    # dp[i]消すなら、vは大きい方から探索する
    for v in range(vmax*i,-1,-1):
      if v-v1>=0:
        dp[v] = min(dp[v], dp[v-v1]+w1)
  ret = 0
  for i in range(len(dp)):
    if dp[i] <= W:
      ret = max(ret, i)
  #print(dp[:30])
  return ret

ans = solve1()

print(ans)


weights, values = [], []

n, w = list(map(int, input().split()))
for _ in range(n):
    w_c, v_c = list(map(int, input().split()))
    weights.append(w_c)
    values.append(v_c)

dp = [[0 for i in range(w + 1)] for i in range(n + 1)]
for i in range(len(values) + 1):
    for j in range(w + 1):
        if i == 0 or j == 0:
            dp[i][j] = 0
        elif weights[i - 1] <= j:
            dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1])
        else:
            dp[i][j] = dp[i - 1][j]

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


n, w = map(int, input().split())
wv = [list(map(int, input().split())) for i in range(n)]
sum_v = sum(wv[i][1] for i in range(n))
sum_w = sum(wv[i][0] for i in range(n))

dp = [[sum_w + 1] * (sum_v + 1) for i in range(n + 1)]
dp[0][0] = 0

for i in range(n):
    for j in range(sum_v + 1):
        if j - wv[i][1] >= 0:
            dp[i + 1][j] = min(dp[i + 1][j], dp[i][j - wv[i][1]] + wv[i][0])
        dp[i + 1][j] = min(dp[i + 1][j], dp[i][j])

ans = 0
for j in range(sum_v + 1):
    if dp[n][j] <= w:
        ans = max(ans, j)
print(ans)


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.InputMismatchException;

public class Main {
	static InputStream is;
	static PrintWriter out;
	static String INPUT = "";

	static void solve()
	{
		int n = ni(), W = ni();
		long[] dp = new long[100005];
		Arrays.fill(dp, Long.MAX_VALUE / 2);
		dp[0] = 0;
		for(int i = 0;i < n;i++){
			int w = ni(), v = ni();
			for(int j = dp.length-1;j >= v;j--){
				dp[j] = Math.min(dp[j], dp[j-v] + w);
			}
		}
		for(int i = dp.length-1;i >= 0;i--){
			if(dp[i] <= W){
				out.println(i);
				return;
			}
		}
	}

	public static void main(String[] args) throws Exception
	{
		long S = System.currentTimeMillis();
		is = INPUT.isEmpty() ? System.in : new ByteArrayInputStream(INPUT.getBytes());
		out = new PrintWriter(System.out);

		solve();
		out.flush();
		long G = System.currentTimeMillis();
		tr(G-S+"ms");
	}

	private static boolean eof()
	{
		if(lenbuf == -1)return true;
		int lptr = ptrbuf;
		while(lptr < lenbuf)if(!isSpaceChar(inbuf[lptr++]))return false;

		try {
			is.mark(1000);
			while(true){
				int b = is.read();
				if(b == -1){
					is.reset();
					return true;
				}else if(!isSpaceChar(b)){
					is.reset();
					return false;
				}
			}
		} catch (IOException e) {
			return true;
		}
	}

	private static byte[] inbuf = new byte[1024];
	static int lenbuf = 0, ptrbuf = 0;

	private static int readByte()
	{
		if(lenbuf == -1)throw new InputMismatchException();
		if(ptrbuf >= lenbuf){
			ptrbuf = 0;
			try { lenbuf = is.read(inbuf); } catch (IOException e) { throw new InputMismatchException(); }
			if(lenbuf <= 0)return -1;
		}
		return inbuf[ptrbuf++];
	}

	private static boolean isSpaceChar(int c) { return !(c >= 33 && c <= 126); }
//	private static boolean isSpaceChar(int c) { return !(c >= 32 && c <= 126); }
	private static int skip() { int b; while((b = readByte()) != -1 && isSpaceChar(b)); return b; }

	private static double nd() { return Double.parseDouble(ns()); }
	private static char nc() { return (char)skip(); }

	private static String ns()
	{
		int b = skip();
		StringBuilder sb = new StringBuilder();
		while(!(isSpaceChar(b))){
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}

	private static char[] ns(int n)
	{
		char[] buf = new char[n];
		int b = skip(), p = 0;
		while(p < n && !(isSpaceChar(b))){
			buf[p++] = (char)b;
			b = readByte();
		}
		return n == p ? buf : Arrays.copyOf(buf, p);
	}

	private static char[][] nm(int n, int m)
	{
		char[][] map = new char[n][];
		for(int i = 0;i < n;i++)map[i] = ns(m);
		return map;
	}

	private static int[] na(int n)
	{
		int[] a = new int[n];
		for(int i = 0;i < n;i++)a[i] = ni();
		return a;
	}

	private static int ni()
	{
		int num = 0, b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private static long nl()
	{
		long num = 0;
		int b;
		boolean minus = false;
		while((b = readByte()) != -1 && !((b >= '0' && b <= '9') || b == '-'));
		if(b == '-'){
			minus = true;
			b = readByte();
		}

		while(true){
			if(b >= '0' && b <= '9'){
				num = num * 10 + (b - '0');
			}else{
				return minus ? -num : num;
			}
			b = readByte();
		}
	}

	private static void tr(Object... o) { if(INPUT.length() != 0)System.out.println(Arrays.deepToString(o)); }
}


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

public class Main implements Runnable
{
    @Override
    public void run() {
        InputReader in = new InputReader(System.in);
        PrintWriter w = new PrintWriter(System.out);
        int N = in.nextInt();
        int W = in.nextInt();
        int[][] arr = new int[N][2];
        for (int i = 0; i < N; i++) {
            arr[i][0] = in.nextInt();
            arr[i][1] = in.nextInt();
        }
        w.println(getRes(arr, W));

        w.flush();
        w.close();
    }

    private static int getRes(int[][] arr, int W) {
        // Arrays.sort(arr, (a1, a2) -> a1[0] - a2[0]);
        int l = arr.length, MAX = 100000;
        int[] haveV = new int[MAX + 1];
        Arrays.fill(haveV, Integer.MAX_VALUE);
        haveV[0] = 0;

        for (int i = 0; i < l; i++) {
            int val = arr[i][1];
            for (int v = MAX - val; v >= 0; v--) {
                if (haveV[v] != Integer.MAX_VALUE && haveV[v] + arr[i][0] <= W) {
                    haveV[v + val] = Math.min(haveV[v + val], haveV[v] + arr[i][0]);
                }
            }
        }

        for (int i = MAX; i >= 0; i--) {
            if (haveV[i] != Integer.MAX_VALUE) {
                return i;
            }
        }
        return -1;
    }

    static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;
        private BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

        public 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++];
        }

        public String nextLine()
        {
            String str = "";
            try
            {
                str = br.readLine();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return str;
        }
        public int nextInt()
        {
            int c = read();

            while(isSpaceChar(c))
                c = read();

            int sgn = 1;

            if (c == '-')
            {
                sgn = -1;
                c = read();
            }

            int res = 0;
            do
            {
                if(c<'0'||c>'9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));

            return res * sgn;
        }

        public long nextLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;

            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            while (!isSpaceChar(c));
            return res * sgn;
        }

        public double nextDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, nextInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, nextInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            }
            while (!isSpaceChar(c));

            return res.toString();
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }

    public static void main(String args[]) throws Exception
    {
        new Thread(null, new Main(),"Main",1<<27).start();
    }

}


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

//atcoder need change class name to Main
//E - Knapsack 2
//stand dp
//this time Weight is to big, can not use it as lenght of dp
//loop from right to left

//https://atcoder.jp/contests/dp/tasks/dp_c

public class Main {
    static StringTokenizer st;
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    public static void main(String[] args) throws IOException {

        int N = nextInt();
        int W = nextInt();

        //no need calc sum, use max 100* 1000
        int maxValue = 100000;
        long[] dp = new long[maxValue+1];
        Arrays.fill(dp, Integer.MAX_VALUE);
        dp[0] = 0;

        for (int i=1; i<=N;  i++) {
            int w = nextInt();
            int v = nextInt();
            for (int j=maxValue; j>=v; j--) {// from right to left
                //from right to left,  make usue only use 1
                //this can be use limit item
                //use count array
                dp[j] = Math.min(dp[j], dp[j-v] + w);
            }
        }

        for (int i = maxValue; i>=0; i--){
            if (dp[i] <=W) {
                System.out.println(i);
                return;
            }
        }
    }

    public static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }
    public static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

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

    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens())
            st = new StringTokenizer(br.readLine().trim());
        return st.nextToken();
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

 class Main{

	public static void main(String[] args) throws IOException {

		FastScanner sc=new FastScanner();
		int n = sc.nextInt();
		long capacity = sc.nextInt();

		long wights[] = new long[n];
		long value[] = new long[n];
		long sum = 0;
		for(int i=0; i<n; i++) {
			wights[i] = sc.nextLong();
			value[i] = sc.nextLong();
			sum = value[i];
		}
		dp = new long[n+1][(int) capacity+1];
		for(int i=0; i<=n; i++) {
			for(int j=0; j<=capacity; j++) {
				if(i == 0 || j == 0)
					dp[i][j] = 0;
			}
		}
		for(int i=1; i<=n; i++) {
			for(int j=1; j<=capacity; j++) {
				if(wights[i-1] <= j) {
					dp[i][j] = Math.max(dp[i-1][(int) (j-wights[i-1])] + value[i-1], dp[i-1][j]);
				}
				else {
					dp[i][j] = dp[i-1][j];
				}
			}
		}
		System.out.println(dp[n][(int) capacity]);

	}

	static long dp[][];

	private static long solve(long[] wights, long[] value, int n, long capacity) {
		if(n == 0 || capacity==0)
			return 0;
		if(dp[n][(int) capacity] != -1)
			return dp[n][(int) capacity];
		if(wights[n-1] <= capacity) {
			return dp[n][(int) capacity] = Math.max(solve(wights, value, n-1, (int) (capacity-wights[n-1]))
					+ value[n-1],
					solve(wights, value, n-1, capacity));
		}
		else {
			return dp[n][(int) capacity] =  solve(wights, value, n-1, capacity);
		}

	}

	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long[] readArrayLong(int n) {
        	long[] a=new long[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
        }
		long nextLong() {
			return Long.parseLong(next());
		}
		String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

 class Main{

	public static void main(String[] args) throws IOException {

		FastScanner sc=new FastScanner();
		int n = sc.nextInt();
		long capacity = sc.nextInt();

		long wights[] = new long[n];
		long value[] = new long[n];
		long sum = 0;
		for(int i=0; i<n; i++) {
			wights[i] = sc.nextLong();
			value[i] = sc.nextLong();
			sum = value[i];
		}
		dp = new long[n+1][(int) sum+1];
		for(int i=0; i<=n; i++) {
			for(int j=0; j<=sum; j++)
				dp[i][j] = -1;
		}
		long v = solve(wights,value,n,capacity);
		System.out.println(v);
	}

	static long dp[][];

	private static long solve(long[] wights, long[] value, int n, long capacity) {
		if(n == 0 || capacity==0)
			return 0;
		if(dp[n][(int) capacity] != -1)
			return dp[n][(int) capacity];
		if(wights[n-1] <= capacity) {
			return dp[n][(int) capacity] = Math.max(solve(wights, value, n-1, (int) (capacity-wights[n-1]))
					+ value[n-1],
					solve(wights, value, n-1, capacity));
		}
		else {
			return dp[n][(int) capacity] =  solve(wights, value, n-1, capacity);
		}

	}

	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long[] readArrayLong(int n) {
        	long[] a=new long[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
        }
		long nextLong() {
			return Long.parseLong(next());
		}
		String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

 class Main{

	public static void main(String[] args) throws IOException {

		FastScanner sc=new FastScanner();
		int n = sc.nextInt();
		long capacity = sc.nextInt();
		dp = new long[n+1][(int) (capacity+1)];
		for(int i=0; i<=n; i++) {
			for(int j=0; j<=capacity; j++)
				dp[i][j] = -1;
		}
		long wights[] = new long[n];
		long value[] = new long[n];
		for(int i=0; i<n; i++) {
			wights[i] = sc.nextLong();
			value[i] = sc.nextLong();
		}
		long v = solve(wights,value,n,capacity);
		System.out.println(v);
	}

	static long dp[][];

	private static long solve(long[] wights, long[] value, int n, long capacity) {
		if(n == 0 || capacity==0)
			return 0;
		if(dp[n][(int) capacity] != -1)
			return dp[n][(int) capacity];
		if(wights[n-1] <= capacity) {
			return dp[n][(int) capacity] = Math.max(solve(wights, value, n-1, (int) (capacity-wights[n-1]))
					+ value[n-1],
					solve(wights, value, n-1, capacity));
		}
		else {
			return dp[n][(int) capacity] =  solve(wights, value, n-1, capacity);
		}

	}

	static void sort(int[] a) {
		ArrayList<Integer> l=new ArrayList<>();
		for (int i:a) l.add(i);
		Collections.sort(l);
		for (int i=0; i<a.length; i++) a[i]=l.get(i);
	}

	static class FastScanner {
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer("");
		String next() {
			while (!st.hasMoreTokens())
				try {
					st=new StringTokenizer(br.readLine());
				} catch (IOException e) {
					e.printStackTrace();
				}
			return st.nextToken();
		}

		int nextInt() {
			return Integer.parseInt(next());
		}
		int[] readArray(int n) {
			int[] a=new int[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
		}
		long[] readArrayLong(int n) {
        	long[] a=new long[n];
			for (int i=0; i<n; i++) a[i]=nextInt();
			return a;
        }
		long nextLong() {
			return Long.parseLong(next());
		}
		String nextLine() {
            String str = "";
            try {
                str = br.readLine();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return str;
        }
	}
}


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

#define all(c) c.begin(),c.end()

template <class T>
struct knapsack {
  T c;
  struct item { T p, w; };
  vector<item> is;
  void add_item(T p, T w) {
    is.push_back({p, w});
  }
  T det(T a, T b, T c, T d) {
    return a * d - b * c;
  }
  T z;
  void expbranch(T p, T w, int s, int t) {
    if (w <= c) {
      if (p >= z) z = p;
      for (; t < is.size(); ++t) {
        if (det(p - z - 1, w - c, is[t].p, is[t].w) < 0) return;
        expbranch(p + is[t].p, w + is[t].w, s, t + 1);
      }
    } else {
      for (; s >= 0; --s) {
        if (det(p - z - 1, w - c, is[s].p, is[s].w) < 0) return;
        expbranch(p - is[s].p, w - is[s].w, s - 1, t);
      }
    }
  }
  T solve() {
    sort(all(is), [](const item &a, const item &b) {
      return a.p * b.w > a.w * b.p;
    });
    T p = 0, w = 0;
    z = 0;
    int b = 0;
    for (; b < is.size() && w <= c; ++b) {
      p += is[b].p;
      w += is[b].w;
    }
    expbranch(p, w, b-1, b);
    return z;
  }
};

int main() {
  int s, n;
  scanf("%d %d", &n, &s);
  knapsack<long long> solver;
  solver.c = s;
  for (int i = 0; i < n; ++i) {
    int v, w;
    scanf("%d %d", &w, &v);
    solver.add_item(v, w);
  }
  printf("%lld\n", solver.solve());
}


#include <algorithm>
#include <cstdio>
#include <vector>

typedef long long int ll;

struct state {
    ll aw;
    ll av;
    state(ll aw = 0, ll av = 0) : aw(aw), av(av) {}
};

struct item {
    int w;
    int v;
    double d;
    item(int w, int v) : w(w), v(v), d((double)v / w) {}
};

int n, w;

ll lower;

std::vector<item> is;
std::vector<state> dp[2];

void add(const std::vector<state> &s, const item &k, std::vector<state> &u,
         ll uw) {
    auto i = s.cbegin();
    auto j = s.cbegin();
    while (i != s.cend() && j != s.cend()) {
        if (i->aw > uw) {
            i = s.cend();
            break;
        }
        ll jav = j->av + k.v;
        ll jaw = j->aw + k.w;
        if (jaw > uw) {
            j = s.cend();
            break;
        }
        if (i->aw <= jaw && i->av >= jav) {
            ++j;
        } else if (i->aw >= jaw && i->av <= jav) {
            ++i;
        } else if (i->aw < jaw) {
            u.push_back(*i++);
        } else {
            u.emplace_back(state(jaw, jav));
            ++j;
        }
    }
    while (i != s.cend()) {
        if (i->aw > uw)
            return;
        u.push_back(*i++);
    }
    while (j != s.cend()) {
        ll jav = j->av + k.v;
        ll jaw = j->aw + k.w;
        if (jaw > uw)
            return;
        u.emplace_back(state(jaw, jav));
        ++j;
    }
}

void remove(const std::vector<state> &s, const item &k, std::vector<state> &u,
            ll uw) {
    auto i = s.cbegin();
    auto j = s.cbegin();
    while (i != s.cend() && j != s.cend()) {
        if (i->aw > uw) {
            i = s.cend();
            break;
        }
        ll jav = j->av - k.v;
        ll jaw = j->aw - k.w;
        if (jaw > uw) {
            j = s.cend();
            break;
        }
        if (i->aw <= jaw && i->av >= jav) {
            ++j;
        } else if (i->aw >= jaw && i->av <= jav) {
            ++i;
        } else if (i->aw < jaw) {
            u.push_back(*i++);
        } else {
            u.emplace_back(state(jaw, jav));
            ++j;
        }
    }
    while (i != s.cend()) {
        if (i->aw > uw)
            return;
        u.push_back(*i++);
    }
    while (j != s.cend()) {
        ll jav = j->av - k.v;
        ll jaw = j->aw - k.w;
        if (jaw > uw)
            return;
        u.emplace_back(state(jaw, jav));
        ++j;
    }
}

ll upper;

inline void shrink(const std::vector<state> &s, double d0, double d1,
                   std::vector<state> &u) {
    for (auto x : s) {
        ll t = (x.aw > w) ? x.av - (x.aw - w) * d0 : x.av + (w - x.aw) * d1;
        if (t >= lower)
            u.push_back(x);
        if (t > upper)
            upper = t;
    }
}

int main() {
    scanf("%d%d", &n, &w);
    is.reserve(200);
    dp[0].reserve(300);
    dp[1].reserve(300);

    is.emplace_back(item(1, 0));

    for (int i = 0; i < n; i++) {
        int ww, vv;
        scanf("%d%d", &ww, &vv);
        if (ww <= w)
            is.emplace_back(item(ww, vv));
    }
    n = is.size() - 1;

    std::sort(is.begin() + 1, is.end(),
              [](const item &x, const item &y) { return x.d > y.d; });
    is.emplace_back(item(1, 0));

    ll aw = 0;
    ll av = 0;
    int ii;
    for (ii = 1; ii <= n; ii++) {
        const item &x = is[ii];
        if (aw + x.w > w)
            break;
        aw += x.w;
        av += x.v;
    }

    dp[0].emplace_back(state(aw, av));

    lower = av;
    ll sumw = w + aw;

    for (int i = ii - 1, j = ii; i > 0 || j <= n;) {
        if (i > 0) {
            sumw -= is[i].w;
            remove(dp[0], is[i], dp[1], sumw);
            dp[0].resize(0);
            lower = (std::upper_bound(
                         dp[1].cbegin(), dp[1].cend(), w,
                         [](int w, const state &x) { return x.aw > w; }) -
                     1)
                        ->av;
            shrink(dp[1], is[i - 1].d, is[j].d, dp[0]);
            dp[1].resize(0);
            --i;
        }

        if (j <= n) {
            add(dp[0], is[j], dp[1], sumw);
            dp[0].resize(0);
            lower = (std::upper_bound(
                         dp[1].cbegin(), dp[1].cend(), w,
                         [](int w, const state &x) { return x.aw > w; }) -
                     1)
                        ->av;
            shrink(dp[1], is[i].d, is[j + 1].d, dp[0]);
            dp[1].resize(0);
            ++j;
        }
        if (lower == upper)
            break;
    }

    lower = (std::upper_bound(dp[0].cbegin(), dp[0].cend(), w,
                              [](int w, const state &x) { return x.aw > w; }) -
             1)
                ->av;
    printf("%lld\n", lower);

    return 0;
}


//#include <bits/stdc++.h>/*
#include <unordered_map>
#include <functional> //greater
#include <algorithm> //sort
#include <iostream>
#include <iterator>
#include <utility> //pair
#include <sstream>
#include <cstring> //memset
#include <complex>
#include <cassert>
#include <random>
#include <cstdio>
#include <string>
#include <vector>
#include <cctype> //isaplha, tolower
#include <deque>
#include <queue>
#include <stack>
#include <array>
#include <cmath> //sqrt, sin
#include <ctime>
#include <list>
#include <map>
#include <set>
//*/

//#define int long long
#define uns unsigned
#define ll long long
#define vi vector<int>
#define pii pair<int,int>
#define pb push_back
#define mp make_pair
#define fi first
#define se second
#define endl '\n'
using namespace std;

template<class T> ostream &operator<<(ostream &os, const pair<T,T> &p){
	return os<<"("<<p.fi<<","<<p.se<<")";}
template<class T> ostream &operator<<(ostream &os, const pair<const T,T> &p){
	return os<<"("<<p.fi<<","<<p.se<<")";}
template<class T> ostream &operator<<(ostream &os, const array<T,3> &p){
	return os<<"("<<p[0]<<","<<p[1]<<","<<p[2]<<")";}
template<class T> ostream &operator<<(ostream &os, const vector<T> &p){
	for(auto x: p) os<<x<<' '; return os;}
#define dbug(x) cerr<<">>>> "<<#x<<" = "<<x<<endl
#define _ <<", "<<
#define FOR(X,L,R) for(int X=L;X<R;X++)
#define FI(I,X) for(auto I=(X).begin();I!=(X).end();I++)
#define print(X) {cerr<<"{ ";FI(I,X)cerr<<*I<<' ';cerr<<"}"<<endl;}
#define mset(V,X) memset(V,X,sizeof(V))
#define all(X) (X).begin(),(X).end()
#define upperb(V,X) (int)(upper_bound(all(V),(X))-V.begin())
#define lowerb(V,X) (int)(lower_bound(all(V),(X))-V.begin())

const double EPS = 1e-9, PI = acos(-1);
const ll LINF = 0x3f3f3f3f3f3f3f3f, mod = 1e9+7;
const int INF = 0x3f3f3f3f, SZ = 2e5+20;

int n,c;
vector<pii> v;//w,v;
int res,aux;
double c2,aux2;
int sf[110];
void bt(int i){
	if(i == n) return;
	//if(sf[i] + aux <= res) return;
	aux2 = 0; c2 = c;
	for(int j=i; j<n && c2; j++){
		if(v[j].fi <= c2){
			c2 -= v[j].fi; aux2 += v[j].se;
		} else {
			aux2 += (v[j].se*c2)/v[j].fi;
			c2 = 0;
		}
	}
	if(aux2 + aux <= res) return;
	if(v[i].fi <= c){
		c -= v[i].fi;
		aux += v[i].se;
		if(aux > res) res = aux;
		bt(i+1);
		aux -= v[i].se;
		c += v[i].fi;
	}
	bt(i+1);
}

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

	cin>>n>>c;
	FOR(i,0,n){
		int x,y; cin>>x>>y;
		//w.pb(x); v.pb(y);
		v.pb({x,y});
	}
	//random_shuffle(all(v));
	sort(all(v),[](pii a, pii b){
		return (a.se+0.0)/a.fi > (b.se+0.0)/b.fi;
	});
	//for(int i=n-1; i>=0; i--) sf[i] = v[i].se+sf[i+1];

	bt(0);
	cout<<res<<endl;

	return 0;
}


/*
    Developer:Pavitra Goyal
*/
#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#include<ext/pb_ds/tree_policy.hpp>
#include<iostream>
#include<algorithm>
#include<unordered_map>
#include<vector>
#include<unordered_set>
#include<set>
#include<map>
#include<utility>
#include<queue>
#include<stack>
#include<chrono>

using namespace std;
using namespace chrono;
using namespace __gnu_pbds;

#define nl                          '\n'
#define int                         long long
#define vi                          vector<int>
#define pi                          pair<int,int>
#define czero(n)                    __builtin_popcountll(n) // count the number of 1's in the bit representation of a number
#define cenzero(n)                  __builtin_ctzll(n) // count the number of zereos from the end of the bit representation of a number until a 1
#define countbegzero(n)             __builtin_clzxll(n)
#define checkparity(n)              __builtin_parityll(n)// checks whether the number of bits are even or odd
#define pb                          push_back
#define mp                          make_pair
#define sp(x,y)                     fixed<<setprecision(y)<<x
#define fastio()                    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
#define mk(arr,n,type)              type *arr=new type[n]; // dynamic allocation of memory
#define del(arr)                    delete []arr;           // deletion of allocated memory
#define testcases(a)                int a; cin>>a; while(a--)
#define FORn(a,b,inc)               for(int i=a;i<b;i+=inc)
#define conscarr(A,n,x)             iota(A,A+n,x)
#define ff                          first
#define ss                          second
#define vpi                         vector<pair<int,int>>
#define vpd                         vector<pair<double,double>>
#define gcd(a,b)                    __gcd(a,b);
#define lcm(a,b)                    (a/gcd(a,b))*b;
#define trace1(x)                   cerr<<#x<<": "<<x<<nl
#define trace2(x, y)                cerr<<#x<<": "<<x<<" | "<<#y<<": "<<y<<nl
#define trace3(x, y, z)             cerr<<#x<<":" <<x<<" | "<<#y<<": "<<y<<" | "<<#z<<": "<<z<<nl
#define trace4(a, b, c, d)          cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<nl
#define trace5(a, b, c, d, e)       cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<nl
#define trace6(a, b, c, d, e, f)    cerr<<#a<<": "<<a<<" | "<<#b<<": "<<b<<" | "<<#c<<": "<<c<<" | "<<#d<<": "<<d<<" | "<<#e<< ": "<<e<<" | "<<#f<<": "<<f<<nl

mt19937                             rng(chrono::steady_clock::now().time_since_epoch().count());
// above line is the best random shuffler ;shuffle(arr,arr+n,rng) <- SYNTAX

/**************************************************************************************************************/
int spf[1000001];
int fac[200001];
inline int read(){int val = 0; char ch;for(ch = getchar(); ch<'0' || ch>'9'; ch = getchar());for(; ch>='0' and ch<='9'; ch = getchar()) val = val*10 + ch - '0';return val;}
inline void take_input(int A[],int n){for(int i=0;i<n;i++){ cin>>A[i];}}
inline void show(int *A,int n){for(int i=0;i<n;i++){cout<<A[i]<<" ";}cout<<nl;}
inline int countDivisibles(int a,int b,int c){if (a%c==0){return (b/c-a/c+1);} return (b/c-a/c);}
inline bool sortbysec(const pair<int,int> &a, const pair<int,int> &b) { return (a.second < b.second); }
inline bool sortbysecdesc(const pair<int,int> &a, const pair<int,int> &b) { return (a.second > b.second); }
inline void swap(int &a,int &b){int temp=a;a=b;b=temp;}
inline void init1d(int *A,int n,int x){for(int i=0;i<n;i++){A[i]=x;} return;}
inline string getstr(int n){ostringstream ss;ss<<n; string res=ss.str();return res;}
inline int modulo(int a,int b){return (b+(a%b))%b;}
inline int getascii(char ch){return (int)ch;}
int expo(int n,int x){int ans=1;while (x>0){if (x&1){ans*=n;} x=x>>1; n=n*n;} return ans;}
int expo(int a, int b, int mod){int res=1; while(b>0){if (b&1)res=(res*a)%mod;a=(a*a)%mod;b=b>>1;} return res;}
int expo(int a,int b,int c,int mod){return expo(a,expo(b,c,mod-1),mod);}
int nCr(int n,int r){int ans=1;if (n-r<r){r=n-r;}for(int i=0;i<r;i++){ans*=(n-i);ans/=(i+1);} return ans;}
int modInverse(int n, int p) { return expo(n, p - 2, p); }
int nCrMod(int n, int r, int p) { if (r == 0) {return 1;} return (fac[n] * modInverse(fac[r], p) % p * modInverse(fac[n - r], p) % p) % p; }
//there exists a O(1) method also in case of many queries.
// on geeksforgeeks
void smallpf(int n=1000001){init1d(spf,1000001,0);spf[1]=0;for(int i=2;i<=1000000;i++){if (spf[i]==0){spf[i]=i;for(int j=2*i;j<=1000000;j+=i){if (spf[j]==0){spf[j]=i;}}}}}
vi sieve(int n) {int*arr = new int[n + 1](); vi vect; for (int i = 2; i <= n; i++)if (arr[i] == 0) {vect.push_back(i); for (int j = 2 * i; j <= n; j += i)arr[j] = 1;} return vect;}
vi pfs(int n){vi ans;while (n>1){ans.pb(spf[n]);n=n/spf[n];}ans.pb(1);return ans;}
int gcdext(int a,int b,int *x,int *y){if (a==0){*x=0,*y=1;return b;}int x1,y1;int gcd=gcdext(b%a,a,&x1,&y1);*x=y1-(b/a)*x1;*y=x1;return gcd;}
int modinv(int b,int m){int x,y;int g=gcdext(b,m,&x,&y);if (g!=1){return -1;}return (x%m+m)%m;}
int moddiv(int a,int b,int m){a=a%m;int inv=modinv(b,m);return (inv*a)%m;}
int modadd(int a,int b,int m){return modulo(modulo((modulo(a,m)+modulo(b,m)),m),m);}
int modsub(int a,int b,int m){return modulo(modulo((modulo(a,m)-modulo(b,m)),m),m);}
template<typename T>
void show_vect(vector<T> v){for(int i=0;i<v.size()-1;i++){cout<<v[i]<<" ";}cout<<v[v.size()-1];cout<<nl;}
template<typename T>
void debug_vect(vector<T> v){for(int i=0;i<v.size();i++){cerr<<v[i]<<" ";}cerr<<nl;}
template<typename T>
void vect_input(vector<T>&v,T n){for(int i=0;i<n;i++){cin>>v[i];}}
template<typename T>
void show_set(set<T> s){for(auto x:s){cout<<x<<" ";}cout<<nl;}

/****************************************************************************************************************/

typedef unsigned long long ull;
typedef tree<int, null_type, less<int>, rb_tree_tag,tree_order_statistics_node_update> ordered_set;
const int rownbr[8]={-1,-1,-1,0,0,1,1,1};
const int colnbr[8]={-1,0,1,-1,1,-1,0,1};
const int rownbr1[4]={1,-1,0,0};
const int colnbr1[8]={0,0,1,-1};
const int MOD=1000000007;
const int inf=1e18;
const int MOD_1=998244353;
const double PI=3.141592653589793238;
// *-------------------------------------------------------------
void p_g_t()
{
    fastio();
    #ifndef ONLINE_JUDGE
    freopen("input.in", " r", stdin);
    freopen("output.in", "w", stdout);
    freopen("error.in","w",stderr);
    #endif
}
// // Driver Code
map<pi,int> dp;
int helper(int n,int *weight,int *val,int w,int ind)
{
    if (w<=0)
        return 0;
    if (ind>n-1)
        return 0;
    if (dp.find(mp(ind,w))!=dp.end())
        return dp[mp(ind,w)];
    if (weight[ind]>w){
        dp[mp(ind,w)]=helper(n,weight,val,w,ind+1);
        return dp[mp(ind,w)];
    }
    dp[mp(ind,w)]=max(val[ind]+helper(n,weight,val,w-weight[ind],ind+1),helper(n,weight,val,w,ind+1));
    return dp[mp(ind,w)];
}
void solve()
{
    int n,w;
    cin>>n>>w;
    mk(weight,n,int);
    mk(val,n,int);
    for(int i=0;i<n;i++)
    {
        cin>>weight[i]>>val[i];
    }
    // memset(dp,-1,sizeof dp);
    cout<<helper(n,weight,val,w,0);
    return;
}
int32_t main()
{
    p_g_t();
    int t=1;
    //take input iff there are multiple tcs
    // cin>>t;
    while (t--)
    {
        solve();
    }
    cerr << "Time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl;
    return 0;
}


#include <iostream>
#define INT_MAX 1000000
#include <cstring>
#include <unordered_map>
#include <vector>
using namespace std;

int main()
{
  int n, w;
  cin >> n >> w;
  vector<int> val(n, 0);
  vector<int> weights(n, 0);
  vector<vector<long>> map(n+1, vector<long>(w+1, 0L));
  for(int i=0; i<n; i++)
    cin >> weights[i] >> val[i];
  for(int i=1; i<n+1; i++)
  {
    for(int j=1; j<w+1; j++)
    {
      if (weights[i-1] <= j)
      	map[i][j] = max(val[i-1]+map[i-1][j-weights[i-1]], map[i-1][j]);
      else
        map[i][j] =  map[i-1][j];
    }
  }
  cout<<map[n][w];
  return 0;
}


#include<bits/stdc++.h>
#define rep(i,n) for (int i=0; i<n; i++)
#define REP(i,x,n) for (int i=x; i<n; i++)
using namespace std;
using vi = vector<int>;
using vvi = vector<vi>;
using ll = long long;
const int mod = 1'000'000'007;
const ll INF = 1LL<<60;

vector<vector<ll>> dp(110, vector<ll>(1010,INF));
vi W(110), V(110);
ll rec(int n, int v){
    if (dp[n][v] != INF) return dp[n][v];
    if (n == 0){
        if (v == 0) return dp[0][0] = 0;
        else return dp[0][v];
    }
    ll res = INF;
    res = min(res, rec(n-1, v));
    if (v >= V[n-1]) res = min(res, rec(n-1, v-V[n-1]) + W[n-1]);
    return dp[n][v] = res;
}

int main(){
    int n, w;
    cin >> n >> w;
    rep(i,n) cin >> W[i] >> V[i];

    ll ans = 0;
    for (ll i=1; i<1010; i++){
        if (rec(n,i) <= w) ans = max(ans, i);
        // rep(i,n){
        //     rep(j,18){
        //         printf("%d", dp[i][j]);
        //     }
        //     printf("\n");
        // }
        // printf("\n");
    }
    cout << ans << endl;
    return 0;
}


#include<stdio.h>
#include<limits.h>
#define d_flag 0
#define MAX 100000
#define INF 1e12
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)<(b)?(b):(a))
#define abs(a) max((a),-(a))
typedef long long int li;

int cp(li a,li b){
  // cp(a,b) means (a<=b)
  if(b== -1)return 1;
  // -1 means INF
  else return(a<=b);
}

int main(){
  int n,W;
  scanf("%d%d",&n,&W);
  int i,j,v[n];
  li w[n],dp[MAX+1];   //dp[v]=w

  for(i=0;i<n;i++){
    scanf("%lld%d",&w[i],&v[i]);
  }

  if(d_flag) printf("%ld\n",LONG_MAX);

  int max_v=0;
  li temp;

  for(i=0;i<=MAX;i++)dp[i]=INF;
  //  if()
  dp[0]=0;
  for(i=0;i<n;i++){
  if(d_flag) printf("i:%d, j=%d downto %d\n",i,max_v,0);
    for(j=max_v+v[i];j>=v[i];j--){
      temp=dp[j-v[i]]+w[i];
      if(d_flag) printf("temp:%ld, W:%d, dp[%d]=%d\n",temp,W,j,dp[j]);
      if(temp<=W && temp<dp[j]){
	dp[j]=temp;
	if(max_v<j){
	  max_v=j;
	}
      }
      if(d_flag) printf("\n");
    }
  }

  if(d_flag){
    for(i=0;i<=max_v;i++)
      printf(" %ld",dp[i]);
    printf("\n");
  }
  printf("%lld",max_v);
}


#include <stdio.h>

#define MIN(a,b) ((a)<(b)?(a):(b))

int n, w;
int W[100];
int V[100];
int dp[100001];

int main(){
  int i, j, r;
  scanf("%d%d", &n, &w);
  for(i=0;i<n;i++) scanf("%d%d", W+i, V+i);
  for(j=1;j<=100000;j++) dp[j] = -1;
  for(i=0;i<n;i++){
    for(j=100000;j>=V[i];j--)
      if(dp[j-V[i]] >= 0) dp[j] = MIN((unsigned) dp[j], (unsigned) (dp[j-V[i]]+W[i]));
  }
  r = 0;
  for(j=0;j<=100000;j++) if(dp[j] >= 0 && dp[j] <= w) r = j;
  printf("%d\n", r);
  return 0;
}


n,w,i,m,a,v;main(){
scanf("%d%d",&n,&w);
m=1e3*n;
int*dp=(int*)calloc(m+1,sizeof(int));
for(i=1;i<=m;i++)dp[i]=w+1;
while(n--){scanf("%d%d",&a,&v);for(i=m;i>=v;i--)dp[i]=(dp[i]>dp[i-v]+a?dp[i-v]+a:dp[i]);}
for(i=m;dp[i]>w;i--);
printf("%d",i);
}


#include <stdio.h>

long int max(long int a, long int b) {
    if (a > b) return a;
    return b;
}

int main() {
    long int n,w;

    scanf("%ld %ld",&n,&w);

    long int val[n];
    long int wt[n];

    for (long int i = 0; i < n; i++) {
        scanf("%ld %ld",&wt[i],&val[i]);
    }

    long int memo[n+1][w+1];
    for (long int i = 0; i < w + 1; i++) {
        memo[0][i] = 0;
    }
    for (long int j = 0; j < n + 1; j++) {
        memo[j][0] = 0;
    }

    for (long int i = 1; i <= n; i++) {

        for (long int espacio = 1; espacio <= w; espacio++) {

            long int maxValWithoutCurr = memo[i - 1][espacio];
            long int maxValWithCurr = 0;

            long int weightOfCurr = wt[i - 1];
            if (espacio >= weightOfCurr) {
                maxValWithCurr = val[i - 1];

                long int espacio_restante = espacio - weightOfCurr;
                maxValWithCurr += memo[i - 1][espacio_restante];
            }

            memo[i][espacio] = max(maxValWithoutCurr, maxValWithCurr);
        }
    }

    printf("%ld \n",memo[n][w]);

    return 0;
}


#include <stdio.h>

int max(int a, int b) {
    if (a > b) return a;
    return b;
}

int main() {
    int n,w;

    scanf("%d %d",&n,&w);

    int val[n];
    int wt[n];

    for (int i = 0; i < n; i++) {
        scanf("%d %d",&wt[i],&val[i]);
    }

    int memo[n+1][w+1];
    for (int i = 0; i < w + 1; i++) {
        memo[0][i] = 0;
    }
    for (int j = 0; j < n + 1; j++) {
        memo[j][0] = 0;
    }

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

        for (int espacio = 1; espacio <= w; espacio++) {

            int maxValWithoutCurr = memo[i - 1][espacio];
            int maxValWithCurr = 0;

            int weightOfCurr = wt[i - 1];
            if (espacio >= weightOfCurr) {
                maxValWithCurr = val[i - 1];

                int espacio_restante = espacio - weightOfCurr;
                maxValWithCurr += memo[i - 1][espacio_restante];
            }

            memo[i][espacio] = max(maxValWithoutCurr, maxValWithCurr);
        }
    }

    printf("%d\n",memo[n][w]);

    return 0;
}


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

typedef struct Temp {
    int v;
    int w;
} Temp;

int comparator(const void *p1, const void *p2);

int comparator(const void *p1, const void *p2) {
    return ((Temp *) p1)->w - ((Temp *) p2)->w;
}

int main() {

    int N, W;
    scanf("%d %d", &N, &W);
    Temp arr[N];

    for (int i = 0; i < N; i++) {
        scanf("%d %d", &arr[i].w, &arr[i].v);
    }

    qsort(arr, N, sizeof(Temp), comparator);

    for (int i = N - 1; i >= 0; i--) {
        if (arr[i].w > W)
            N--;

    }

    int ans = 0;

    int value, weight, boolean;
    int final = (int) pow(2, N);

    for (int i = 0; i < final; i++) {
        value = weight = 0;
        boolean = 1;

        for (int j = 0; j < N; j++) {
            if (i & (1 << j) ) {
                if ((weight += arr[N - 1 - j].w) <= W) {
                    value += arr[N - 1 - j].v;
                } else {
                    boolean = 0;
                    break;
                }

            }

        }

        if (boolean && ans < value) {
            ans = value;
        }

    }

    printf("%d", ans);

    exit(0);
}


"use strict";

function main(input){
  const args = input.trim().split('\n').map(_=>_.split(' ').map(_=>parseInt(_,10)));
  const n = args[0][0];
  const w_max = args[0][1];
  const items = args.slice(1);

  const dp = Array(100001).fill(1000000001); // 価値をiにするための最小容量
  dp[0] = 0;
  for(let i=0; i<n; i++){
    const weight = items[i][0];
    const value = items[i][1];
    for(let v=100000; v>=value; v--){
      dp[v] = Math.min(dp[v], dp[v-value] + weight);
    }
  }

  for(let i=100000; i>=0; i--){
    if(dp[i] <= w_max){
      console.log(i);
      return;
    }
  }
}

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


var MAX_VALUE = 1000;

var inputRaw = require('fs').readFileSync('/dev/stdin', 'utf8');
var rows = inputRaw.trim().split('\n');
var row1 = rows[0].split(' ').map(Number);
var N = row1[0];
var W = row1[1];
var list = rows.slice(1).map(r => r.split(' ').map(Number));
var dp = Array.from({ length: N + 1 }, _ => Array( N * MAX_VALUE + 1).fill(Infinity));
dp[0][0] = 0;

function solve() {

  for (var i = 0; i < N; i++) {
    for (var j = 0; j <= N * MAX_VALUE; j++) {
      if (list[i][1] <= j) {
        var a = dp[i][j - list[i][1]] + list[i][0];
        var b = dp[i][j];
        dp[i + 1][j] = Math.min(a, b);
      } else {
        dp[i + 1][j] = dp[i][j];
      }
    }
  }

  var result = 0;
  for (var i = 0; i <= N * MAX_VALUE; i++) if (dp[N][i] <= W) result = i;
  return result;
}

console.log(solve());


function main(input){
  const lines = input.split('\n');
  const NW = lines.shift().split(' ').map(x => parseInt(x));
  const N = NW[0]
  const W = NW[1]
  const items = lines.map(line => line.split(' ').map(x => parseInt(x)));

  const first = items.shift();
  const first_weight = first[0];
  const first_value = first[1];
  var value_sum = first_value;
  dp = [0]

  for(var i=1;i<=value_sum;i++){
    dp[i]=first_weight;
  }

  for(var i=0;i<items.length;i++){
    var current_weight = items[i][0];
    var current_value = items[i][1];
    value_sum += current_value;

  //console.log(dp);

    for(var value=value_sum;value>0;value--){

      if(value >= current_value){
        var prev_weight = dp[value - current_value];
        if(dp[value]==undefined){
          dp[value] = current_weight + prev_weight;
        }else{
          dp[value] = Math.min(prev_weight+current_weight, dp[value]);
        }
      }else{
        if(dp[value]==undefined){
          dp[value]=current_weight;
        }else{
          dp[value]=Math.min(current_weight, dp[value]);
        }
     }
    }
  }

  var result = 0;

//  for(var i=value_sum;i>=0;i--){
//    if(dp[i]<=W){
//      result = i;
//      break;
//    }
//  }

  for(var i=dp.length-1;i>=0;i--){
    if(dp[i]<=W){
      result = i;
      break;
    }
  }

  //console.log(dp);

//  console.log(result==90);
  console.log(result);

}

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


'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });

    main();
});

function readline() {
    return inputString[currentLine++];
}

function getArray(str) {
    return str.split(' ').map(x => Number(x));
}

function getInt(str) {
    return Number(str);
}

function getStrArray(str) {
    return str.split(' ').map(x => x);
}

function create2DArray(row, col,  filler = 0) {
    return Array(row)
        .fill(filler)
        .map(() => Array(col).fill(filler));
}
// ---------------------------------------

function main() {
    let [n, w] = getArray(readline());
    const arr = [];
    const dp = create2DArray(n+1, w+1, 0)

    let c = n;

    while(c--) {
        arr.push(getArray(readline()));
    }

    function solve(n1, w1) {
        //console.log(n1, w1);
        if (n1 < 0 || w1 <= 0) {
            return 0;
        }
        if (dp[n1][w1]) {
            return dp[n1][w1];
        }
        if (w1 >= arr[n1][0]) {
            dp[n1][w1] = Math.max(arr[n1][1] + solve(n1 - 1, w1 - arr[n1][0]), solve(n1 - 1, w1));
        } else {
            dp[n1][w1] = solve(n1 - 1, w1);
        }
        return dp[n1][w1];
    }

    console.log(solve(n-1, w));
}


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

// Your code here!
const max = (a)=>{
    let i = a.length;
    let max=-Infinity;
    while (i--) {
        if (a[i] > max)max = a[i];
    }
    return max;
}
const min = (a)=>{
    let i = a.length;
    let max=Infinity;
    while (i--) {
        if (a[i] < max)max = a[i];
    }
    return max;
}
const Main = (p)=>{
	p = p.split("\n");//2 or more
	//let N = parseInt(p[0]);//N
	const N = parseInt(p[0].split(" ")[0]);//N M
	const W = parseInt(p[0].split(" ")[1]);//N M
	//let h = (p[1].split(" ").map(Number));//a1 a2 a3...

	let w = new Array(N);
	let v = new Array(N);
	//let c=new Array(N);
    //let z=new Array(N);
    for(let i=0;i<N;i++){
        let h = (p[i+1].split(" ").map(Number));
        w[i]=h[0];
        v[i]=h[1];
    }

    const maxv=30000;
	let m = new Array(N+1);
    //console.log(N,W,w,v);return;
    m[0]=new Array(maxv+1).fill(Infinity);
    m[0][0]=0;
    for(let i=0;i<=N;i++){
        m[i+1]=m[i].concat();
        for(let j=0;j<=maxv;j++){
            if(j-v[i]>=0){
                //console.log(m[i][j-w[i]]+v[i],m[i][j])
                m[i+1][j]=Math.min(m[i][j-v[i]]+w[i],m[i][j]);
            }

        }
        //console.log(i,m[i])
    }
	//console.log(m[N][maxv-1]);
	let i=maxv;
	while(m[N][i--]>W);//console.log(m[N][i--]);
	console.log(i+1);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


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

// Your code here!
const max = (a)=>{
    let i = a.length;
    let max=-Infinity;
    while (i--) {
        if (a[i] > max)max = a[i];
    }
    return max;
}
const min = (a)=>{
    let i = a.length;
    let max=Infinity;
    while (i--) {
        if (a[i] < max)max = a[i];
    }
    return max;
}
const Main = (p)=>{
	p = p.split("\n");//2 or more
	//let N = parseInt(p[0]);//N
	const N = parseInt(p[0].split(" ")[0]);//N M
	const W = parseInt(p[0].split(" ")[1]);//N M
	//let h = (p[1].split(" ").map(Number));//a1 a2 a3...

	let w = new Array(N);
	let v = new Array(N);
	//let c=new Array(N);
    //let z=new Array(N);
    for(let i=0;i<N;i++){
        let h = (p[i+1].split(" ").map(Number));
        w[i]=h[0];
        v[i]=h[1];
    }

    const maxv=100;
	let m = new Array(N+1);
    //console.log(N,W,w,v);return;
    m[0]=new Array(maxv+1).fill(Infinity);
    m[0][0]=0;
    for(let i=0;i<=N;i++){
        m[i+1]=m[i].concat();
        for(let j=0;j<=maxv;j++){
            if(j-v[i]>=0){
                //console.log(m[i][j-w[i]]+v[i],m[i][j])
                m[i+1][j]=Math.min(m[i][j-v[i]]+w[i],m[i][j]);
            }

        }
        //console.log(i,m[i])
    }
	//console.log(m[N][maxv-1]);
	let i=maxv;
	while(m[N][i--]>W);//console.log(m[N][i--]);
	console.log(i+1);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());


package main

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

var DEBUG = true

func main() {
	defer Flush()

	N := readi()
	W := readi()
	w := make([]int, N)
	v := make([]int, N)
	for i := range w {
		w[i] = readi()
		v[i] = readi()
	}

	var maxv int
	for i := range v {
		maxv += v[i]
	}
	dp := make([]int, maxv+1)
	for i := range dp {
		dp[i] = -1
	}
	dp[0] = 0

	for i := range w {
		ww := w[i]
		vv := v[i]
		for j := maxv; 0 <= j; j-- {
			if dp[j] == -1 {
				continue
			}
			nj := j + vv
			nw := dp[j] + ww
			if maxv < nj {
				continue
			}
			if dp[nj] == -1 {
				dp[nj] = nw
			} else {
				dp[nj] = min(dp[nj], nw)
			}
		}
	}
	for j := maxv; 0 <= j; j-- {
		if dp[j] == -1 || W < dp[j] {
			continue
		}
		println(j)
		return
	}
}

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

// IO helper functions

// Returns next token from input.  It must be initialized by SetInput()
// before the first call.
var nextToken func() ([]byte, error)
var nextLine func() ([]byte, error)

// Holds a buffer for output.  It must be initialized by SetOutput().
// All IO fucntions (read*() and [e]print*()) should write to OutputWriter
// instead of this.
var OutputBuffer *bufio.Writer

// Holds an io.Writer.  It must be initialized by SetOutput()
var OutputWriter io.Writer

// Set IO functions for interactive input/output.
func SetInteractive(w io.Writer, r io.Reader) {
	SetUnbefferedInput(r)
	OutputBuffer = nil
	OutputWriter = w
}

// Setup OutputBuffer and OutputWriter.
func SetOutput(w io.Writer) {
	OutputBuffer = bufio.NewWriter(w)
	OutputWriter = OutputBuffer
}

// Flushes OutputBuffer
func Flush() {
	if OutputBuffer != nil {
		OutputBuffer.Flush()
	}
}

// Returns true if c is a white space
func IsSpace(c byte) bool {
	switch c {
	case '\t', '\n', '\v', '\f', '\r', ' ':
		return true
	}
	return false
}

func IsNewLine(c byte) bool {
	switch c {
	case '\n', '\r':
		return true
	}
	return false
}

// Setup nextToken with input buffer.
func SetInput(r io.Reader) {
	buf := new(bytes.Buffer)
	var b []byte

	var i int
	rest := func() ([]byte, error) {
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		return b[j:i], nil
	}
	initial := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextToken = rest
		return rest()
	}
	nextToken = initial

	restLn := func() ([]byte, error) {
		for i < len(b) && IsNewLine(b[i]) {
			i++
		}
		if i == len(b) {
			return nil, io.ErrUnexpectedEOF
		}
		j := i
		for i < len(b) && !IsNewLine(b[i]) {
			i++
		}
		return b[j:i], nil
	}

	initialLn := func() ([]byte, error) {
		io.Copy(buf, r)
		b = buf.Bytes()
		nextLine = restLn
		return restLn()
	}
	nextLine = initialLn
}

// Setup nextToken without input buffer.
func SetUnbefferedInput(r io.Reader) {
	buf := bufio.NewReader(r)
	var b []byte

	var i int
	nextToken = func() ([]byte, error) {
		var err error
		if i == len(b) {
			b, err = buf.ReadBytes('\n')
			if err != nil {
				return nil, err
			}
			i = 0
			j := len(b) - 1
			for 0 <= j && IsSpace(b[j]) {
				j--
			}
			b = b[0 : j+1]
		}
		for i < len(b) && IsSpace(b[i]) {
			i++
		}
		j := i
		for i < len(b) && !IsSpace(b[i]) {
			i++
		}
		if i == j {
			return nil, io.ErrUnexpectedEOF
		}
		return b[j:i], nil
	}
}

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

// IO functions

// Reads next token and return it as []byte
func readb() []byte {
	b, err := nextToken()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Reads next token and return it as string
func reads() string {
	return string(readb())
}

// Read next line as []byte.  Trailing '\n' will not be included.
// See also comments on readb()
func readbln() []byte {
	b, err := nextLine()
	if err != nil {
		panic(err)
	}
	return b[:len(b):len(b)]
}

// Read next line as string
func readsln() string {
	return string(readbln())
}

// Reads next token and return it as int64
func readll() int64 {
	i, err := strconv.ParseInt(reads(), 10, 64)
	if err != nil {
		panic(err.Error())
	}
	return i
}

// Reads next token and return it as int
func readi() int {
	return int(readll())
}

// Reads next token and return it as float64
func readf() float64 {
	f, err := strconv.ParseFloat(reads(), 64)
	if err != nil {
		panic(err.Error())
	}
	return f
}

// Write args to OutputWriter with the format f
func printf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(OutputWriter, f, args...)
}

// Write args to OutputWriter without format
func println(args ...interface{}) (int, error) {
	return fmt.Fprintln(OutputWriter, args...)
}

// Write args to stderr with the format f
func eprintf(f string, args ...interface{}) (int, error) {
	return fmt.Fprintf(os.Stderr, f, args...)
}

// Write args to stderr without format
func eprintln(args ...interface{}) (int, error) {
	return fmt.Fprintln(os.Stderr, args...)
}

func dbgf(f string, args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintf(os.Stderr, f, args...)
}

func dbg(args ...interface{}) {
	if !DEBUG {
		return
	}
	fmt.Fprintln(os.Stderr, args...)
}

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

// Utilities

func sumSlice(a []int) int {
	var res int
	for _, v := range a {
		res += v
	}
	return res
}

func sumSlicell(a []int64) int64 {
	var res int64
	for _, v := range a {
		res += v
	}
	return res
}

func readInts(N int) (int, []int) {
	if N == 0 {
		N = readi()
	}
	a := make([]int, N)
	for i := range a {
		a[i] = readi()
	}
	return N, a
}

func readIntsll(N int) (int, []int64) {
	if N == 0 {
		N = readi()
	}
	a := make([]int64, N)
	for i := range a {
		a[i] = readll()
	}
	return N, a
}

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

// Simple math functions

const (
	// big prime
	INF  = 1000000007
	INF2 = 1000000009
	INF3 = 998244353
)

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func minll(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

func minf(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func maxll(a, b int64) int64 {
	if a < b {
		return b
	}
	return a
}

func maxf(a, b float64) float64 {
	if a < b {
		return b
	}
	return a
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func absll(a int64) int64 {
	if a < 0 {
		return -a
	}
	return a
}

func absf(a float64) float64 {
	if a < 0 {
		return -a
	}
	return a
}

// egcd(a, b) returns d, x, y:
//   d is gcd(a,b)
//   x, y are  integers that satisfy ax + by = d
func egcd(a, b int) (int, int, int) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcd(b, a%b)
	return d, y, x - a/b*y
}

func egcdll(a, b int64) (int64, int64, int64) {
	if b == 0 {
		return a, 1, 0
	}
	d, x, y := egcdll(b, a%b)
	return d, y, x - a/b*y
}

func gcd(a, b int) int {
	d, _, _ := egcd(a, b)
	return d
}

func gcdll(a, b int64) int64 {
	d, _, _ := egcdll(a, b)
	return d
}

// set up IO functions
func init() {
	// for non-interactive
	SetInput(os.Stdin)
	SetOutput(os.Stdout)

	// Enable below when interactive.  Its ok to leave above intact.
	// SetInteractive(os.Stdout, os.Stdin)
}


package main

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

func main() {
  input := Input{bufio.NewReaderSize(os.Stdin,100)}
  n,u := input.NextInts()
  dp := make([]int,100002)
  for i:=1;i<100002;i++ { dp[i] = 2*u }
  for i:=0;i<n;i++ {
    w,v := input.NextInts()
    for j:=100001;j>v-1;j-- {
      t := dp[j-v]+w
      if dp[j] > t { dp[j] = t }
    }
  }
  for i:=100001;i>-1;i-- {
    if dp[i] <= u { fmt.Println(i);return }
  }
}

type Input struct { reader *bufio.Reader }
func(i *Input) NextLine() string {
  var buffer []byte
  for {
    line,isPrefix,err := i.reader.ReadLine()
    if err != nil { panic(err) }
    buffer = append(buffer,line...)
    if !isPrefix { break }
  }
  return string(buffer)
}
func(i *Input) NextInts() (int,int) {
  s := strings.Split(i.NextLine()," ")
  a,_ := strconv.Atoi(s[0])
  b,_ := strconv.Atoi(s[1])
  return a,b
}


package main

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

var INF = math.MaxInt32
var INF64 = math.MaxInt64

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

func max(a, b int) int {
	if a < b {
		return b
	}
	return a
}

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func readLineNums(bf *bufio.Reader) []int {
	line, _ := bf.ReadString('\n')
	line = strings.Trim(line, "\n")
	fields := strings.Split(line, " ")
	nums := []int{}
	for _, field := range fields {
		num, _ := strconv.Atoi(field)
		nums = append(nums, num)
	}
	return nums
}

func readLineFloats(bf *bufio.Reader) []float64 {
	line, _ := bf.ReadString('\n')
	line = strings.Trim(line, "\n")
	fields := strings.Split(line, " ")
	nums := []float64{}
	for _, field := range fields {
		num, _ := strconv.ParseFloat(field, 64)
		nums = append(nums, num)
	}
	return nums
}

func readLineStrs(bf *bufio.Reader) []string {
	line, _ := bf.ReadString('\n')
	line = strings.Trim(line, "\n")
	return strings.Split(line, " ")
}

func main() {
	bf := bufio.NewReader(os.Stdin)
	nw := readLineNums(bf)
	N, W := nw[0], nw[1]
	Ws := make([]int, 0)
	Vs := make([]int, 0)
	for i:=0; i<N; i++ {
		wv := readLineNums(bf)
		Ws = append(Ws, wv[0])
		Vs = append(Vs, wv[1])
	}

	V := 0
	for _, v := range Vs {
		V += v
	}

	dp := make([]int, V+1) // dp[i]: 表示产生价值为i, 需要的最少背包容量
	for i:=1; i<=V; i++ {
		dp[i] = INF
	}

	for i:=0; i<N; i++ {
		wi := Ws[i]
		vi := Vs[i]
		for v:=V; v>=vi; v-- {
			dp[v] = min(dp[v], dp[v-vi]+wi)
		}
	}

	ans := 0
	for i:=0; i<=V; i++ {
		if dp[i] <= W {
			ans = max(ans, i)
		}
	}
	fmt.Println(ans)
}


package main

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

func main() {
	const valueMax = int(1e5)
	const inf = int(1e18)
	N, W := readI(), readI()
	w, v := make([]int, N+1), make([]int, N+1)
	for i := 1; i <= N; i++ {
		w[i], v[i] = readI(), readI()
	}

	//dp[i][j] = iまでの商品を価値j以上で選んだ際の最小の重量
	dp := make([][]int, N+1)
	for i := 0; i <= N; i++ {
		dp[i] = make([]int, valueMax+1)
		for j := 0; j <= valueMax; j++ {
			dp[i][j] = inf
		}
	}
	dp[0][0] = 0
	for i := 0; i <= N; i++ {
		if i == 0 {
			continue
		}
		for j := 1; j <= valueMax; j++ {
			if j-v[i] >= 0 {
				dp[i][j] = min(dp[i-1][j-v[i]]+w[i], dp[i-1][j])
			} else {
				dp[i][j] = dp[i-1][j]
			}
		}
	}
	ans := valueMax
	for dp[N][ans] > W && ans > 0 {
		ans--
	}
	fmt.Println(ans)
}

func min(a ...int) int {
	m := a[0]
	for i := 1; i < len(a); i++ {
		if m > a[i] {
			m = a[i]
		}
	}
	return m
}

/*-----------Input utils-----------*/

var sc = bufio.NewScanner(os.Stdin)

func init() {
	if len(os.Args) >= 2 {
		if os.Args[1] == "debug" {
			debug()
		}
	}
	const buf = 200100
	sc.Split(bufio.ScanWords)
	sc.Buffer(make([]byte, buf), buf)
}

func debug() {
	testFile, err := os.Open("./test/sample-1.in")
	if err != nil {
		fmt.Fprintln(os.Stderr, "There is no testfile.")
		os.Exit(1)
	}
	sc = bufio.NewScanner(testFile)
}

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

func readR() []rune {
	return []rune(readS())
}

func readI() int {
	i, _ := strconv.Atoi(readS())
	return i
}

func readF() float64 {
	f, _ := strconv.ParseFloat(readS(), 64)
	return f
}