jiahuimbzuai/CoQuIR huggingface dataset:
//  [rust]
#![allow(unused_imports)]

use text_io::*;
use proconio::*;
use std::collections::*;
use std::process::exit;
use std::cmp::*;
use itertools::Itertools;

fn main() {
    let a: String = read!();
    let b: String = read!();
    let a = a.chars().collect_vec();
    let b = b.chars().collect_vec();
    let mut c:usize=0;
    for i in 0..a.len() {
        for j in 0..a.len() {
            if a[j]==b[(i+j)%a.len()]{
                c+=1;
            }
        }
        if c==a.len() {
            println!("Yes");
            exit(0)
        }
        c=0;
    }
    println!("No")
}
//  [typescript]
import { readFileSync } from "fs";

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

const main = (input: string[][]) => {
  const S = input[0][0];
  const T = input[1][0];

  for (let i = 0; i <= S.length; i++) {
    if (`${S.slice(i)}${S.slice(0, i)}` === T) {
      return "Yes";
    }
  }

  return "No";
};

console.log(main(read()));
//  [python]
n, a, b = map(int, input().split())

amount = 0
for v in range(1, n+1):
    tmp = v
    s = 0
    while True:
        t = int(tmp % 10)
        tmp /= 10
        s += t
        if tmp == 0:
            break

    if a <= s and s <= b:
        amount += v

print(amount)
//  [python]
import math
 
n, a, b = map(int, input().split())
 
sum_all = 0
for i in range(1, n + 1):
    sum_n = 0
    m = i
    while(m > 0):
        sum_n += math.floor(m % 10)
        m /= 10
    if a <= sum_n <= b:
        sum_all += i
 
print(sum_all)
//  [python]
N, A, B = [int(x) for x in input().split()]
ResSum = 0

for i in range(1, N+1):
    Nsum = 0
    temp = i
    while (temp > 0):
        Nsum += int(temp % 10)
        temp /= 10
    if Nsum >= A and Nsum <= B:
        ResSum += i

print(ResSum)
//  [java]
import java.util.*;

public class Main {

    public static void main(String[] args) {
	// write your code here
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int a = sc.nextInt();
        int b = sc.nextInt();

        int ans = 0;
        for(int i = 1; i <= n; i++) {
            int sum = 0;
            int num = i;
            while(num != 0){
                sum += num % 10;
                num /= 10;
            }
            System.err.printf("num: %d, sum: %d\n", i, sum);
            if(sum >= a && sum <= b)
                ans += i;
        }

        System.out.println(ans);
    }
}
//  [java]
import java.util.*;
import java.util.stream.*;
class Main {
    public static void main(String[] args) {
        int N,A,B;
        Scanner input;
        input = new Scanner(System.in);
        N = input.nextInt();
        A = input.nextInt();
        B = input.nextInt();
        int ans = 0;
        for (int i = 1; i <= N; i++){
          String tmp = String.valueOf(i);
          String[] sa = tmp.split("");
          int[] ia = Stream.of(sa).mapToInt(Integer::parseInt).toArray();
          int sum = java.util.Arrays.stream(ia).sum();
          if (A <= sum && sum <= B){
            ans += i;
          }
        }
        System.out.println(ans);
    }
}
//  [java]
import java.util.*;
import java.util.stream.Stream;
class Main {
    public static void main(String[] args) {
        int N,A,B;
        Scanner input;
        input = new Scanner(System.in);
        N = input.nextInt();
        A = input.nextInt();
        B = input.nextInt();
        int ans = 0;
        for (int i = 1; i <= N; i++){
          String tmp = String.valueOf(i);
          String[] sa = tmp.split("");
          int[] ia = Stream.of(sa).mapToInt(Integer::parseInt).toArray();
          int sum = 0;
          for (int j = 0; j < ia.length; j++){
            sum += ia[j];
          }
          if (A <= sum && sum <= B){
            ans += i;
          }
        }
        System.out.println(ans);
    }
}
//  [cpp]

//1�ȏ�N�ȉ��̐����̂����A10�i�@�ł̊e�s�̘a��A�ȏ�B�ȉ��ł������̂̑��a�����߂Ă�������

#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int main() {
	int A, B, sum = 0, tmp = 0, ans = 0;
	int N;
	cin >> N >> A >> B;

	for (int j = 1; j <= N; j++) {
		for (int i = 1; i <= j / 10 + 1; i++) {
			if (i == 1) sum += (j - tmp) % 10;
			else        sum += (j - tmp) % (int)pow(10, i) / (int)pow(10, i - 1);
			tmp += (j - tmp) % (int)pow(10, i);
		}
		if (sum >= A && sum <= B) ans += j;
		sum = tmp = 0;
	}

	cout << ans << endl;

	return 0;
}
//  [cpp]
#include<bits/stdc++.h>
#define _GLIBCXX_DEBUG
using namespace std;
using ll= long long;
using ld= long double;
using P =pair<ll,ll>;


//マクロ
//forループ関係
//引数は、(ループ内変数,動く範囲)か(ループ内変数,始めの数,終わりの数)、のどちらか
//Dがついてないものはループ変数は1ずつインクリメントされ、Dがついてるものはループ変数は1ずつデクリメントされる
#define REP(i,n) for(ll i=0;i<=(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=(ll)(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=(ll)(b);i--)
//xにはvectorなどのコンテナ
#define ALL(x) (x).begin(),(x).end() //sortなどの引数を省略したい
#define sort(a) sort(ALL(a))//sortの省略
#define SIZE(x) ((ll)(x).size()) //sizeをsize_tからllに直しておく
#define MAX(x) *max_element(ALL(x)) //最大値を求める
#define MIN(x) *min_element(ALL(x)) //最小値を求める
//定数
#define INF 1000000000000 //10^12:極めて大きい値,∞
#define MOD 10000007 //10^9+7:合同式の法
#define MAXR 100000 //10^5:配列の最大のrange(素数列挙などで使用)
//略記
#define in(T, x) T x;cin >> x;//Tは型,xが入力値
#define vec(T,a,n,x) vector<T> a(n,x);
#define vec2(T,a,n,m) vector<vector<T>> a(n,vector<T>(m));
#define PB push_back //vectorヘの挿入
#define MP make_pair //pairのコンストラクタ
#define F first //pairの一つ目の要素
#define S second //pairの二つ目の要素
#define out(x) cout << x << endl//出力
#define bout(b) if(b){out("Yes");}else{out("No");}//真偽問題に対する出力
#define ain(T, a, n) vector<T> a(n);REP(i, n){cin >> a[i];}//配列の宣言と入力
#define a2in(T1, a, T2, b, n) vector<T1> a(n);vector<T2> b(n);REP(i, n){cin >> a[i] >> b[i];}//2つの配列を同時宣言、入力

template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }//dp表とかで最大値更新するやつ
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }//最小値更新


signed main(){
  in(ll,N);
  in(ll,A);
  in(ll,B);
  ll wa=0;
  REP(i,N){
    ll ketawa=0;
    ll I=i;
    REP(j,10000){
      
      ketawa+=I%10;
      I/=10;
      
    }
    if(ketawa>=A && ketawa<=B)wa+=i;
  }
  out(wa);
   

}
//  [cpp]
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
 
int N_DIGIT = 5;
 
int main(){
  int N, A, B;
  cin >> N >> A >> B;
  
  vector<int> N_num(N_DIGIT), ans;
  
  for (int i = A; i <= B; i++){
    for (int j = 1; j <= N; j++){
      int n_sum = 0;
      int temp = j;
      for (int k = 0; k < N_DIGIT; k++){
        N_num.at(k) = temp / pow(10, (N_DIGIT-k-1));
        temp -= N_num.at(k) * pow(10, (N_DIGIT-k-1));
      }
      for (int n : N_num)	n_sum += n;
      if (n_sum == i)		ans.push_back(j);
    }
  } 
  int result = 0;
  for (int t = 0; t < ans.size(); t++) result += ans.at(t);
  cout << result << endl;
 
 
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(void){
  char buf[32] = { 0 };
  int N,A,B;
  int n = 0; //桁数
  int sum = 0; //位の和
  int total = 0;
  
  //入力読み込み
  fgets(buf, sizeof(buf), stdin);
  sscanf(buf, "%d %d %d", &N, &A, &B);
  
  n = log10((double)N);
  
  for(int num = 1; num <= N; num++){
    int n_tmp = n;
    int num_tmp = num;
    sum = 0;
    while(n_tmp >= 0){
      sum += num_tmp / (int)pow(10, n_tmp);
      num_tmp = num_tmp % (int)pow(10, n_tmp);
      n_tmp--;
    }
    if(sum >= A && sum <= B) total += num;
  }
  
  printf("%d\n", total);
  return 0;
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main(void){
  char buf[32] = { 0 };
  int N,A,B;
  int n = 0; //桁数
  int sum = 0; //位の和
  int total = 0;
  
  //入力読み込み
  fgets(buf, sizeof(buf), stdin);
  sscanf(buf, "%d %d %d", &N, &A, &B);
  
  n = log10((double)N);
  
  for(int num = 1; num <= N; num++){
    int n_tmp = n;
    int num_tmp = num;
    int pow_tmp = (int)pow(10, n_tmp);
    sum = 0;
    for(;n_tmp >= 0; n_tmp--,pow_tmp = (int)pow(10, n_tmp)){
      if(num_tmp < pow_tmp) continue;
      sum += num_tmp / pow_tmp;
      num_tmp = num_tmp % pow_tmp;   
    }
    if(sum >= A && sum <= B) total += num;
  }
  
  printf("%d\n", total);
  return 0;
}
//  [c]
#include<stdio.h>

int main(){

int N,A,B,ans=0;
scanf("%d%d%d",&N,&A,&B);
if (N==10000&&A>=1)
{
  ans += 10000;
  N = 9999;
}

for (int i = 0; i < 10; i++){
  for (int j = 0; j < 10; j++){
    for (int k = 0; k < 10; k++){
      for (int l = 0; l < 10; l++){
        if (N<i*1000+j*100+k*10+l){  goto loop_break;}
        
        int check = i + j + k + l;

        if (A<=check&&check<=B){  ans+=(i*1000+j*100+k*10+l);}
      }
    }
  }
}

loop_break:
printf("%d",ans);
return 0;

}
//  [javascript]
// inputに入力データ全体が入る
function Main(input) {
	var args = input.split(" ");
	var N = parseInt(args[0],10);
	var min = parseInt(args[1],10);
	var max = parseInt(args[2],10);
	var array = [];
	var sum = 0;
	var answer = 0;

	for(var i = 0;i <= N;i++){
		sum = 0;
		var num_string = i + "";
		var num_array = num_string.split("");
		for(var j in num_array){
		sum += parseInt(num_array[j],10);
		}
		if(sum >= min && sum<= max) array.push(i);
	}

	for(var i =0;i < array.length; i++){
		answer += array[i];
	}
	//出力
	console.log(answer);
}

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

// inputに入力データ全体が入る
function Main(input) {
	input = input.split(" ");

	var N = input[0];
	var A = input[1];
	var B = input[2];

	var sum = 0;
	for (var i = 0 ; i <= N; i++) {
		var digitSum = getSumOfDigits(i);
		if(A <= digitSum && digitSum <= B) {
			sum += i;
		}
	}

	console.log(sum);
}

function getSumOfDigits(value) {
	var s = 0;
	while (value) {
	    s += value % 10;
	    value = Math.floor(value / 10);
	}
	return s;
}

//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input) {
    var N = input[0].split(" ")[0]-0;
    var a = input[0].split(" ")[1]-0;
    var b = input[0].split(" ")[2]-0;
  var ans = 0;
  for(var i=1;i<=N;i++){
    var sum = i.toString().split("").reduce((a,b)=>(a-0)+(b-0));
    if(a<=sum && b>=sum) ans += i;
  }
  console.log(ans);
    
}
main(require('fs').readFileSync('/dev/stdin', 'utf8').trim().split("\n"))
//  [go]
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	var n, a, b int

	fmt.Scan(&n, &a, &b)

	answer := 0
	ch := make(chan int, 1024)

	for i := 1; i <= n; i++ {
		go sum(i, a, b, ch)
	}

	for i := 1; i <= n; i++ {
		answer += <-ch
	}

	fmt.Println(answer)
}

func sum(i int, a int, b int, ch chan int) {
	iStr := strconv.Itoa(i)
	splitedIStr := strings.Split(iStr, "")

	sum := 0
	for _, j := range splitedIStr {
		jInt, _ := strconv.Atoi(j)
		sum += jInt
	}

	if (a <= sum) && (sum <= b) {
		ch <- i
	} else {
		ch <- 0
	}
}
//  [go]
package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	var n, a, b int

	fmt.Scan(&n, &a, &b)

	answer := 0
	ch := make(chan int)

	for i := 1; i <= n; i++ {
		go sum(i, a, b, ch)
	}

	for i := 1; i <= n; i++ {
		answer += <-ch
	}

	fmt.Println(answer)
}

func sum(i int, a int, b int, ch chan int) {
	iStr := strconv.Itoa(i)
	splitedIStr := strings.Split(iStr, "")

	sum := 0
	for _, j := range splitedIStr {
		jInt, _ := strconv.Atoi(j)
		sum += jInt
	}

	if (a <= sum) && (sum <= b) {
		ch <- i
	} else {
		ch <- 0
	}
}
//  [go]
package main

import (
	"fmt"
	"sync"
)

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

	var wg sync.WaitGroup
	valueChan := make(chan int, 100)

	for i := n; i > 0; i-- {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()

			digitTotal := 0
			tempValue := i
			for tempValue > 0 {
				digitTotal += tempValue%10
				tempValue /= 10
			}

			if a <= digitTotal && digitTotal <= b {
				valueChan <- i
			}
		}(i)
	}

	go func() {
		wg.Wait()
		close(valueChan)
	}()

	sum := 0
	for v := range valueChan {
		sum += v
	}

	fmt.Println(sum)
}
//  [ruby]
require 'prime'
require 'set'
require 'tsort'
include Math
ALP = ('a'..'z').to_a
INF = 0xffffffffffffffff
def max(a,b);              a > b ? a : b                              end
def min(a,b);              a < b ?  a : b                             end
def swap(a,b);             a, b = b, a                                end
def gif;                   gets.to_i                                  end
def gff;                   gets.to_f                                  end
def gsf;                   gets.chomp                                 end
def gi;                    gets.split.map(&:to_i)                     end
def gf;                    gets.split.map(&:to_f)                     end
def gs;                    gets.chomp.split.map(&:to_s)               end
def gc;                    gets.chomp.split('')                       end
def pr(num);               num.prime_division                         end
def pr?(num);              Prime.prime?(num)                          end
def digit(num);            num.to_s.length                            end
def array(s,ini=nil);      Array.new(s){ini}                          end
def darray(s1,s2,ini=nil); Array.new(s1){Array.new(s2){ini}}          end
def rep(num);              num.times{|i|yield(i)}                     end
def repl(st,en,n=1);       st.step(en,n){|i|yield(i)}                 end

n, a, b = gi
ct = 0
repl 1,n do |num|
tmp = (eval num.to_s.split('').join('+'))
ct += num if tmp >= a && tmp <= b
end
puts ct
//  [ruby]
n, a, b = gets.split.map(&:to_i)
all = 0

(1..n).each do |i|
  if (a <= i.to_s.split('').map(&:to_i).inject(:+)) && (b >= i.to_s.split('').map(&:to_i).inject(:+))
    all = all + i
  end
end


puts all
//  [ruby]
N,A,B = gets.split.map(&:to_i)
a = 0
for i in 0..N
    if A <= i.to_s.split("").map{|s| s.to_i}.inject(:+) && i.to_s.split("").map{|s| s.to_i}.inject(:+) <= B
        a += i
    end
end

puts a
//  [rust]
/// input macro
/// https://qiita.com/tanakh/items/0ba42c7ca36cd29d0ac8
///
/// # Example
///
#[macro_export]
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)*}
    };
}

#[macro_export]
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)*}
    };
}

#[macro_export]
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, usize1) => {
        read_value!($next, usize) - 1
    };

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

use std::io::Write;

macro_rules! eprintln (
    ($($arg:tt)*) => { {
        let r = writeln!(&mut ::std::io::stderr(), $($arg)*);
        r.expect("failed printing to stderr");
    } }
);

fn main() {
    input! {
        nab: [u32; 3],
    }

    let n = nab[0];
    let a = nab[1];
    let b = nab[2];

    let mut ans = 0;
    for i in 1..n + 1 {
        let sum = i.to_string().chars().into_iter()
            .fold(0, |sum, x| sum + x.to_digit(10).unwrap());

        if a <= sum && sum <= b {
            ans += i;
            eprintln!("{}: {} <= {} <= {}", i, a, sum, b);
        }
    }

    println!("{}", ans);
}
//  [rust]
use std::io::prelude::*;
use std::str::FromStr;
pub struct Scanner<R: Read>(R);
impl<R: Read> Scanner<R> {
    pub fn new(reader: R) -> Self {
        Self(reader)
    }
    pub fn read<T: FromStr>(&mut self) -> T {
        let token = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| (b as char).is_whitespace())
            .take_while(|&b| !(b as char).is_whitespace())
            .collect::<Vec<u8>>();
        unsafe { std::str::from_utf8_unchecked(token.as_slice()) }
            .parse()
            .ok()
            .expect("Can't parse it.")
    }
    pub fn vec<T: FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
}
fn main() {
    let (stdin, stdout) = (std::io::stdin(), std::io::stdout());
    let mut sc = Scanner::new(stdin.lock());
    let mut out = std::io::BufWriter::new(stdout.lock());
    solve(&mut sc, &mut out);
    out.flush().ok().unwrap();
}
fn solve(sc: &mut Scanner<std::io::StdinLock>, out: &mut std::io::BufWriter<std::io::StdoutLock>) {
    let (n, a, b): (u32, u32, u32) = (sc.read(), sc.read(), sc.read());

    println!(
        "{}",
        (1..=n)
            .filter(|s| {
                let sum: u32 = s.to_string().chars().map(|c| (c as u8 - b'0') as u32).sum();
                sum >= a && sum <= b
            })
            .sum::<u32>()
    );
}
//  [swift]
import Foundation
func indexSum(_ num: Int) -> Int {
    var sum = 0
    var arr = Array(String(num))
    for i in 0 ..< arr.count {
        var k = Int(String(arr[i]))
        sum += k ?? 0
    }
    return sum
}
let rd = readLine()!.split(separator: " ").map({Int($0)!})
let N = rd[0]
var sum = 0

for i in 1 ... N {
    if rd[1] <= indexSum(i) && indexSum(i) <= rd[2] {
        sum += i
    }
}
print(sum)
//  [swift]
import Foundation

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

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

//var min, min2, count: Int!
//for i in 1...10 {
//    let x = Int(readLine()!)!
//    if i == 1 {
//        min = x
//        count = 1
//    } else if x < min {
//        min2 = min
//        min = x
//        count = 1
//    } else if x == min && count == 1 {
//        min2 = x
//        count = 2
//    }
//}
//print(min2)

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

let input = readIntSplit(by: " ")
let (N, A, B) = (input[0], input[1], input[2])
var ans = 0
for i in 1...N {
    if A...B ~= (String(i).toArray().reduce(0){$0+Int($1)!}) {
        ans += i
    }
}
print(ans)
//  [swift]
import Foundation
func toTuple<T>(_ args: [T]) -> (T, T, T) { (args[0], args[1], args[2]) }
func readInts() -> [Int] { readLine()!.split(separator: " ").map { Int($0)! } }

let (n, a, b) = toTuple(readInts())
let ans = (1...n).map {
  var sum = 0
  for c in String($0) { sum += Int(String(c))! }
  if sum >= a && sum <= b { return $0 }
  else { return 0 }
}.reduce(0, +)
print(ans)
//  [typescript]
// general helpers
const debug = (message?: any, ...optionalParams: any[]) => {
  if (process.env.LOCAL_DEBUG === '1') console.log(message, ...optionalParams)
}

// helpers
const parseLines = (
  lines: string[]
): any => {
  const [N, A, B] = lines[0].split(' ')
  const obj = { N, A, B }
  debug(obj)
  return obj
}

// solver
export const solve = (lines: string[]): string => {
  const { N, A, B } = parseLines(lines)
  let result = 0
  for (let i = 1; i <= N; i++) {
    const digitSum = `${i}`.split("").reduce((prev, current) => prev += +current, 0)
    if (A <= digitSum && digitSum <= B) {
      result += i
    }
  }
  return `${result}`
}

// main
const main = (lines: string[]) => {
  console.log(solve(lines))
}

// exec main function for submit
if (process.env.LOCAL_DEBUG !== '1') {
  const { stdin: input, stdout: output } = process
  input.resume()
  input.setEncoding('utf8')
  const lines: string[] = []
  require('readline')
    .createInterface({ input, output })
    .on('line', (line: string) => lines.push(line))
    .on('close', () => main(lines))
}
//  [typescript]
"use strict";

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

function main(input) {
  const [n, a, b] = input.trim().split(" ").map(Number);

  let ans = 0;
  for (let i = 1; i <= n; i++) {
    const sumOfEachDigit = String(i).split("").map(Number).reduce((p, c) => p + c);
    if (sumOfEachDigit >= a && sumOfEachDigit <= b) {
      ans += i;
    }
  }

  console.log(ans);
}
//  [typescript]
[n,a,b]=require('fs').readFileSync('/dev/stdin','utf8').split(' ').map(n=>n|0)
for(c=0,i=0;++i<=n;a<=r&&r<=b&&(c+=i))
	r=(i+'').split('').map(n=>n|0).reduce((a,b)=>a+b)
console.log(c)
//  [python]
# coding: utf-8
import sys
input = sys.stdin.readline

def f(n, wlimit):
    dp = [-1] * (wlimit + 1)
    dp[0] = 0
    for i in range(1, n + 1):
        wi, vi = map(int, input().rstrip().split())
        dp_ = list(dp)
        for w in range(wlimit + 1):
            if dp[w] >= 0:
                w_ = w + wi
                v_ = dp[w] + vi
                if w_ <= wlimit and dp[w_] < v_:
                    dp_[w_] = v_
        dp = dp_
    return(max(dp))

n, w = map(int, input().rstrip().split()) # 1 <= n <= 100, 1 <= w <= 10^5

print(f(n, w))
//  [python]
#メモ化したもの(修正版)
n,w=map(int,input().split())
a=[]
dp=[]
for i in range(n):
   a.append(list(map(int,input().split())))
for k in range(n+1):
   dp.append([-1]*(w+1))
def rec(i,j):
   if dp[i][j]>=0:
       return dp[i][j]
   if i==n:
       res=0
   elif j<a[i][0]:
       res=rec(i+1,j)
   else:
       res=max(rec(i+1,j),rec(i+1,j-a[i][0])+a[i][1])
   dp[i][j]=res
   return res
print(rec(0,w))
//  [java]
import java.util.*;

public class Main
{
  static int n, w;
  static int[] W, V;
  static Long[][] memo;
  public static void main(String[] args)
  {
	Scanner in = new Scanner(System.in);
    n = in.nextInt();
    w = in.nextInt();
    W = new int[n];
    V = new int[n];
    for (int i = 0; i < n; i++)
    {
      W[i] = in.nextInt();
      V[i] = in.nextInt();
    }
    
    memo = new Long[n][w+1];
    System.out.println(dp(0, 0));    
    in.close();
  }
  
  public static long dp(int at, int free)
  {
    if (free > w)
      return -(long)1e14;
    if (at == n)
      return 0;
    if (memo[at][free] != null)
      return memo[at][free];
    
    long ans = 0;
    ans = Math.max(ans, V[at]+dp(at+1, free+W[at]));
    ans = Math.max(ans, dp(at+1, free));
    return memo[at][free] = ans;
 }
}
//  [java]

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

public class Main implements Closeable {

  private InputReader in = new InputReader(System.in);
  private PrintWriter out = new PrintWriter(System.out);
  
  public void solve() {
    n = in.ni();
    W = in.ni();
    weight = new int[n];
    value = new long[n];
    for (int i = 0; i < n; i++) {
      weight[i] = in.ni();
      value[i] = in.nl();
    }
    dp = new Long[n][W + 1];
    out.println(recurse(0, 0));
  }
  
  private int n, W;
  private int[] weight;
  private long[] value;
  private Long[][] dp;
  
  private long recurse(int idx, int current) {
    if (idx == n) return 0;
    
    if (dp[idx][current] != null) return dp[idx][current];
    
    long ans = recurse(idx + 1, current);
    if (current + weight[idx] <= W) {
      ans = Math.max(ans, value[idx] + recurse(idx + 1, weight[idx] + current));
    }
    return dp[idx][current] = ans;
  }

  @Override
  public void close() throws IOException {
    in.close();
    out.close();
  }

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

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

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

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

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

    public void close() throws IOException {
      reader.close();
    }
  }

  public static void main(String[] args) throws IOException {
    try (Main instance = new Main()) {
      instance.solve();
    }
  }
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
using lli = long long int;
#define filein freopen ("in.txt", "r", stdin)
#define fileout freopen ("out.txt", "w", stdout)
#define dbg(args...) do {cerr << #args << " : "; debug(args); } while(false)
#define all(v) ((v).begin()),((v).end())
#define size(x) (int) x.size() 
#define pb emplace_back
#define mp make_pair
#define PI 3.14159265
#define mod 1000000007
void debug () {cerr << endl;}
template< class T > T gcd(T a, T b) { return (b != 0 ? gcd<T>(b, a%b) : a); }
template< class T > T lcm(T a, T b) { return (a / gcd<T>(a, b) * b); }
template < typename T, typename ... hello>void debug( T arg, const hello &... rest) {cerr << arg << ' ';debug(rest...);}
const int maxN = 1e5 + 10;
lli dp[101][maxN];
lli get_res(int n,int w,vector<int> prod,vector<int> prices){
	if(n == 0 or w == 0){
		return 0;
	}
	if(dp[n][w] != -1){
		return dp[n][w];
	}
	if(prod[n - 1] > w){
		return dp[n][w] = get_res(n - 1,w,prod,prices);
	}
	return dp[n][w] = max(prices[n - 1] + get_res(n - 1,w - prod[n - 1],prod,prices),get_res(n - 1,w,prod,prices));
}
int main(){
	ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n,w;
    cin >> n >> w;
    vector<int> prod,prices;
    memset(dp,-1,sizeof(dp));
    for(int i = 0;i < n; i++){
		int x,y;
		cin >> x >> y;
		prod.pb(x),prices.pb(y);
	}
	cout << get_res(n,w,prod,prices);
}
//  [cpp]
#include<bits/stdc++.h>
#include <string>
using namespace std;
#define ll long long
vector<vector<ll>> mp;

ll find(ll i,vector<ll> arr,vector<ll> profit,ll w){

  if(i<0||w<=0)return 0;
  if(mp[i][w]!=-1)return mp[i][w];
  if(arr[i]>w){
  	return mp[i][w]=find(i-1,arr,profit,w);
  }else{
  	return mp[i][w]=max(find(i-1,arr,profit,w-arr[i])+profit[i],find(i-1,arr,profit,w));
  }
  
  
}

int main(){

  ll n,w;
  cin>>n>>w;
  mp.clear();
  mp.resize(101,vector<ll>(100001,-1));
  vector<ll> arr(n),profit(n);
  for(int i=0;i<n;i++)
    cin>>arr[i],cin>>profit[i];
  cout<<find(n-1,arr,profit,w<100001?w:100000)<<endl;
  return 0;
  
}
//  [cpp]
#include<bits/stdc++.h>
using namespace std;
#define bitCount(num)  __builtin_popcount(num)
#define pb push_back
#define ll long long
#define bye return 0;
#define f(i,a,b) for( long long i=a;i<b;i++)
#define testCases long long t;cin>>t; while(t--)
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);
#define newLine <<"\n"
#define all(x) (x).begin(), (x).end()
#define vll vector<long long>




ll knapSack_Memo(vector<pair<int,ll>> p,vector<vector<ll>> &dp, int currSum, int n)
{
     

	if(n==0|| currSum==0) 
		return dp[n][currSum]=0;


if(dp[n][currSum]!=-1) return dp[n][currSum];


  if(p[n-1].first<= currSum) 
  	{
  		ll ans1= p[n-1].second+knapSack_Memo(p,dp,currSum-p[n-1].first,n-1);
  		ll ans2=knapSack_Memo(p,dp,currSum,n-1);
  		return dp[n][currSum] =max(ans1,ans2);
  	}

  else return dp[n][currSum]=knapSack_Memo(p,dp,currSum,n-1);

}



int main()
{
    fast

    int n,w;
    cin>>n>>w;
    vector<pair<int,ll>> p_(n);

    f(i,0,n)
    {
    	int a;
    	ll b;
    	cin>>a>>b;
    	p_[i]={a,b};
    }
    // vector<pair<ll,ll>> p;

//     sort(p_.begin(),p_.end());
// // cout<<p.size()<<endl;
//     for(int i=n-1;i>=0;i--)p.pb(make_pair(p_[i].first,p_[i].second));
    // cout<<p.size()<<endl;
    vector<vector<ll>> dp(n+1, vector<ll>(w+1,-1));
    cout<<knapSack_Memo(p_,dp,w,n);
    // cout<<endl;
    // showDP(dp);




   
    bye
}
//  [c]
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stdint.h>
#include<stdbool.h>
#include<math.h>
#include<time.h>
#define ll long long
#define min(a,b) ((a)>(b)?(b):(a))
#define max(a,b) ((a)>(b)?(a):(b))
#define maax(a,b,c) max((a), max((b), (c)))
int n, w, v[111][2];
ll x[111][111111];

ll nyaan(int i, int j){
    if(j <= 0) return 0;
    if(i >= n) return 0;
    if(x[i][j] >= 0) return x[i][j];
    if(j < v[i][0]) return x[i][j] = nyaan(i+1, j);
    return x[i][j] = max(nyaan(i+1, j), v[i][1] + nyaan(i+1, j - v[i][0]));
}

int main(){
    scanf("%d%d", &n, &w);
    for(int i=0; i<n; i++){
        scanf("%d%d", &v[i][0], &v[i][1]);
    }
    for(int i=0;i<111;i++){
        for(int j=0; j<111111; j++){
            x[i][j] = -1;
        }
    }
    printf("%lld\n",nyaan(0,w));
}
//  [c]
#include <stdio.h>
long long int ans[101][100001];
long long int max(long long int a,long long int b)
{
	if(a>b) return a;
	return b;
}
long long int knap(int n,int w,int weight[],int v[])
{

	if(ans[n][w]!=-1)
	{
		return ans[n][w];
	}
	else if(w==0||n==0)
	{
		ans[n][w]=0;
		return ans[n][w];
	}	
	long long int r=knap(n-1,w,weight,v);
	if(w-weight[n-1]>=0)
	{
		r=max(r,v[n-1]+knap(n-1,w-weight[n-1],weight,v));
	}
	ans[n][w]=r;
	return ans[n][w];
}
int main(void)
{
	int n,w;
	scanf("%d %d",&n,&w);
	int weight[n];
	int v[n];
	for (int i = 0; i < n; ++i)
	{
		scanf("%d %d",&weight[i],&v[i]);
	}
	for (int i = 0; i <=n; ++i)
	{
		for (int j = 0; j <=w; ++j)
		{
			ans[i][j]=-1;
		}
	}
	printf("%lld\n", knap(n,w,weight,v));
	
}
//  [c]
#include <stdio.h>
#include <inttypes.h>

int N, W;
int w[128], v[128];

int64_t asumikana[128][114514];

int64_t kugyu(int pos, int nokori) {
	int64_t kotae, neko;
	if (pos >= N) return 0;
	if (asumikana[pos][nokori]) return ~asumikana[pos][nokori];

	kotae = kugyu(pos + 1, nokori);
	if (nokori >= w[pos]) {
		neko = kugyu(pos + 1, nokori - w[pos]) + v[pos];
		if (neko > kotae) kotae = neko;
	}
	return ~(asumikana[pos][nokori] = ~kotae);
}

int main(void) {
	int i;
	if (scanf("%d%d", &N, &W) != 2) return 1;
	for (i = 0; i < N; i++) {
		if (scanf("%d%d", &w[i], &v[i]) != 2) return 1;
	}
	printf("%" PRId64 "\n", kugyu(0, W));
	return 0;
}
//  [javascript]
'use strict'

const INF = 900719925474099 // Number.MAX_SAFE_INTEGER / 10;

function Main(input){
	let temp = input.trim().split('\n');
	let temp2 = temp[0].split(' ').map((v)=>parseInt(v));
	let n = temp2.shift();
	let w = temp2.shift();
	let wv = new Array(n);

	for(let i=0;i<n;i++){
		wv[i] = temp[i+1].split(' ').map((v)=>parseInt(v));
	}

	let dp = [...new Array(n+10)].map(()=>(new Array(w + 10).fill(0)));
	
	//渡すDP
	for(let i=0;i<n;i++){
		for(let j=0;j<=w;j++){
			//入れる
			if(j + wv[i][0] <= w){
				dp[i+1][j+wv[i][0]] = Math.max(dp[i+1][j+wv[i][0]], dp[i][j] + wv[i][1]);
			}

			//入れない
			dp[i+1][j] = Math.max(dp[i+1][j],dp[i][j]);

		}
		//console.log(dp);
	}
	console.log(Math.max(...dp[n]));
}

Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";
function Main(input) {
    let lines = input.split("\n");
    let nw = lines.shift().split(/\s/).map((v) => v - 0);
    let N = nw[0] - 0, W = nw[1] - 0;
    let wv = new Array(N);
    for (let n = 0; n < N; n++) {
        wv[n] = lines.shift().split(/\s/).map((v) => v - 0);
    }
    let dp = new Array(N + 1).fill(0).map(() => new Array(W + 1).fill(0));
    for (let n = 0; n < N; n++) {
        for (let sum_w = 0; sum_w <= W; ++sum_w) {
            if (sum_w - wv[n][0] >= 0) {
                dp[n + 1][sum_w] = Math.max(dp[n + 1][sum_w], dp[n][sum_w - wv[n][0]] + wv[n][1]);
            }
            dp[n + 1][sum_w] = Math.max(dp[n + 1][sum_w], dp[n][sum_w]);
        }
    }
    console.log(dp[N][W]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
/*
N	W
6	15

w	v
6	5
5	6
6	4
6	6
3	5
7	2

	0	1	2	3	4	5	6	7	8	9	10	11	12	13	14	15
0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0	0
1	0	0	0	0	0	0	5	5	5	5	5	5	5	5	5	5
2	0	0	0	0	0	6	6	6	6	6	6	11	11	11	11	11
3	0	0	0	0	0	6	6	6	6	6	6	11	11	11	11	11
4	0	0	0	0	0	6	6	6	6	6	6	12	12	12	12	12
5	0	0	0	5	5	6	6	6	11	11	11	12	12	12	17	17
6	0	0	0	5	5	6	6	6	11	11	11	12	12	12	17	17
*/
//  [javascript]
"use strict";
function Main(input) {
    let lines = input.split("\n");
    let nw = lines.shift().split(/\s/).map((v) => v - 0);
    let N = nw[0] - 0, W = nw[1] - 0;
    let wv = new Array(N);
    for (let n = 0; n < N; n++) {
        wv[n] = lines.shift().split(/\s/).map((v) => v - 0);
    }
    let dp = new Array(N + 1).fill(0).map(() => new Array(W + 1).fill(0));
    for (let n = 0; n < N; n++) {
        for (let sum_w = 0; sum_w <= W; ++sum_w) {
            if (sum_w - wv[n][0] >= 0) {
                dp[n + 1][sum_w] = Math.max(dp[n + 1][sum_w], dp[n][sum_w - wv[n][0]] + wv[n][1]);
            }
            dp[n + 1][sum_w] = Math.max(dp[n + 1][sum_w], dp[n][sum_w]);
        }
    }
    console.log(dp[N][W]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [go]
// Package main provides
//
// File:  d.go
// Author: ymiyamoto
//
// Created on Thu Jan 10 20:08:18 2019
//
package main

import (
	"fmt"
	"sort"
)

type pair struct {
	w, v int
}

func max(slice ...int) int {
	sort.Ints(slice)
	return slice[len(slice)-1]
}

func main() {
	var N, W int
	fmt.Scan(&N, &W)

	arr := make([]pair, N)
	for i := range arr {
		fmt.Scan(&arr[i].w, &arr[i].v)
	}

	dp := make([][]int, N+1)
	for i := range dp {
		dp[i] = make([]int, W+1)
	}
	dp[0][0] = 0

	for i := range arr {
		iw, iv := arr[i].w, arr[i].v
		for w := range dp[i] {
			if w-iw >= 0 {
				dp[i+1][w] = max(dp[i][w], dp[i][w-iw]+iv)
			} else {
				dp[i+1][w] = dp[i][w]
			}
		}
	}

	ans := 0
	for i := range dp[N] {
		if dp[N][i] != 1<<60 {
			ans = max(ans, dp[N][i])
		}
	}

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

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

var sc = bufio.NewScanner(os.Stdin)

func oneInt() int {
	var a int
	fmt.Scan(&a)
	return a
}

func oneInt64() int64 {
	var a int64
	fmt.Scan(&a)
	return a
}

func oneStr() string {
	var a string
	fmt.Scan(&a)
	return a
}

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

func scanNums() (nums []int) {
	s := nextLine()
	numStr := strings.Split(s, " ")

	for _, n := range numStr {
		i, _ := strconv.Atoi(n)
		nums = append(nums, i)
	}
	return nums
}

func scanStrings() (strs []string) {
	s := nextLine()
	list := strings.Split(s, " ")
	strs = append(strs, list...)
	return strs
}

func abs(a int) int {
	return int(math.Abs(float64(a)))
}

func pow(p, q int) int {
	return int(math.Pow(float64(p), float64(q)))
}

func min(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton min() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Min(float64(res), float64(nums[i])))
	}
	return res
}

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func strSearch(a []string, b string) bool {
	for i := 0; i < len(a); i++ {
		if a[i] == b {
			return true
		}
	}
	return false
}

func sortAsc(a []int) []int {
	sort.Ints(a)
	return a
}

func sortDesc(a []int) []int {
	sort.Sort(sort.Reverse(sort.IntSlice(a)))
	return a
}

func gcd(a, b int) int {
	if b == 0 {
		return a
	}
	return gcd(b, a%b)
}

func lcm(a, b int) int {
	if a == 0 && b == 0 {
		return 0
	}
	return a * b / gcd(a, b)
}

func permutation(n int, k int) int {
	v := 1
	if 0 < k && k <= n {
		for i := 0; i < k; i++ {
			v *= (n - i)
		}
	} else if k > n {
		v = 0
	}
	return v
}

func factorial(n int) int {
	return permutation(n, n-1)
}

func combination(n int, k int) int {
	return permutation(n, k) / factorial(k)
}

func homogeneous(n int, k int) int {
	return combination(n+k-1, k)
}

type key struct {
	w uint
	v uint
}

type dpKey struct {
	i int
	w uint
}

var table map[int]key
var dp [][]uint

func main() {
	N := oneInt()
	W := uint(oneInt())

	table = make(map[int]key)
	dp = make([][]uint, N+1)
	for index := 0; index <= N; index++ {
		dp[index] = make([]uint, 110000)
	}

	for index := 0; index < N; index++ {
		table[index] = key{uint(oneInt()), uint(oneInt())}
	}

	for index := 0; index < N; index++ {
		var windex uint
		for windex = 0; windex <= W; windex++ {
			if table[index].w <= windex { // 対象の荷物が入るかチェック
				temp := table[index].v + dp[index][windex- table[index].w] 
				chmax(&dp[index+1][windex], temp)
			} //入るなら入れてみて、余った空間に入る最大の勝ちのものをDPテーブルから持ってくる
			chmax(&dp[index+1][windex], dp[index][windex])
		}
	}
	fmt.Print(dp[N][W])
}

func chmax(a *uint, b uint) bool {
	if *a < b {
		*a = b
		return true
	}
	return false
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func max(nums ...int) int {
	if len(nums) == 0 {
		panic("funciton max() requires at least one argument.")
	}
	res := nums[0]
	for i := 0; i < len(nums); i++ {
		res = int(math.Max(float64(res), float64(nums[i])))
	}
	return res
}

func main() {
	var n, W int
	fmt.Scan(&n, &W)
	w := make([]int, n)
	v := make([]int, n)
	for i := 0; i < n; i++ {
		fmt.Scan(&w[i], &v[i])
	}
	dp := make([][]int, n+1)
	dp[0] = make([]int, W+1)

	// solve
	for i := 0; i < n; i++ {
		dp[i+1] = make([]int, W+1)

		for j := 1; j <= W; j++ {
			if j-w[i] >= 0 {
				dp[i+1][j] = max(dp[i+1][j], dp[i][j-w[i]]+v[i])
			}
			dp[i+1][j] = max(dp[i+1][j], dp[i][j])
		}
	}
	fmt.Println(dp[n][W])
}
//  [ruby]
n,w = gets.chomp.split(" ").map(&:to_i)
dp = Array.new(w+1,0)
for i in 1..n
  wei,val = gets.chomp.split(" ").map(&:to_i)
  for j in wei..w
    if dp[w-j]+val > dp[w-j+wei]
      dp[w-j+wei] = dp[w-j]+val
    end
  end
end
puts dp[-1]
//  [ruby]
weight=[]
value=[]
n,m=gets.split.map(&:to_i)
dp=Array.new(n+1,0)
for i in 0..n+1
    dp[i]=Array.new(1000000,0)
end

items=[]

#dpループ
for i in 0..n-1
    weight[i],value[i]=gets.split.map(&:to_i)
    item=[weight[i],value[i]]
    for w in 0..m
        #各状況における重さを全列挙し、選ばない場合は前の状況そのまま、選んだ
        #場合はその重さから荷物を引いた状態にvalueをたす
        if w>=item[0]
            #選ばない場合→dp[i][w]がそのまま遷移　、選んだ場合→dp[i][w]
            dp[i+1][w]=[dp[i][w-item[0]]+item[1],dp[i][w]].max
        else
         dp[i+1][w]=dp[i][w]
         end
    end
 end
    puts dp[n][m]
//  [ruby]
n,w_max = gets.split.map(&:to_i)
weight,value = gets.split.map(&:to_i)

dp=[0] * w_max
for i in 0..weight-1
  dp[i]=0
end
for i in weight..w_max
  dp[i]=value
end

for i in 1...n
  pre_dp = dp.clone
  weight,value = gets.split.map(&:to_i)
  for j in weight..w_max
    dp[j] = pre_dp[j-weight] + value
    dp[j] = pre_dp[j] if dp[j]<pre_dp[j]
  end
end
puts dp.last
//  [rust]
macro_rules! input {
    (source = $s:expr, $($r:tt)*) => {
        let mut iter = $s.split_whitespace();
        input_inner!{iter, $($r)*}
    };
    ($($r:tt)*) => {
        #[allow(unused_mut)]
        let mut 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")
    };
}

#[derive(Debug)]
struct Load {
    pub weight: i64,
    pub value: i64,
}

fn main() {
    input! {
        n: i64,
        w: i64,
        _loads: [(i64, i64); n as usize]
    }
    let mut loads = vec![];
    for l in _loads {
        loads.push(Load {
            weight: l.0,
            value: l.1,
        })
    }
    let mut cache = vec![vec![None; w as usize + 1]; n as usize];
    let v = max_value(&loads, &mut cache, n - 1, w);
    println!("{}", v)
}

fn max_value(loads: &Vec<Load>, cache: &mut Vec<Vec<Option<i64>>>, k: i64, y: i64) -> i64 {
    if k < 0 || y < 0 {
        0
    } else {
        if let Some(v) = cache[k as usize][y as usize] {
            return v;
        }
        let using = if y - loads[k as usize].weight < 0 {
            0
        } else {
            max_value(loads, cache, k - 1, y - loads[k as usize].weight) + loads[k as usize].value
        };
        let not_using = max_value(loads, cache, k - 1, y);
        let value = i64::max(using, not_using);
        cache[k as usize][y as usize] = Some(value);
        value
    }
}
//  [rust]
#![allow(non_snake_case)]

use std::cmp;

#[allow(dead_code)]
pub struct Scanner<'a> {
    _buf: &'a str,
    iter: ::std::str::SplitWhitespace<'a>,
}

#[allow(dead_code)]
impl<'a> Scanner<'a> {
    pub fn new(buf: &'a str) -> Self {
        Scanner {
            _buf: buf,
            iter: buf.split_whitespace(),
        }
    }

    pub fn array<T>(&mut self, n: usize) -> Vec<T>
        where T: ::std::str::FromStr,
              T::Err: ::std::fmt::Debug,
    {
        let mut res = Vec::with_capacity(n);
        for _ in 0..n {
            res.push(self.value());
        }
        res
    }

    pub fn value<T>(&mut self) -> T
        where T: ::std::str::FromStr,
              T::Err: ::std::fmt::Debug,
    {
        self.next().parse().unwrap()
    }

    pub fn chars(&mut self) -> Vec<char> {
        self.next().chars().collect()
    }

    fn next(&mut self) -> &str {
        self.iter.next().unwrap()
    }
}

struct Solver {
    W: Vec<i64>,
    V: Vec<i64>,
    memo: Vec<Vec<Option<i64>>>,
}

impl Solver {
    fn new(W: Vec<i64>, V: Vec<i64>) -> Self {
        Solver {
            W: W,
            V: V,
            memo: vec![vec![None; 100001]; 101],
        }
    }

    /// i個までで重さj以下
    fn f(&mut self, i: i64, j: i64) -> i64 {
        if i == 0 { return 0; }

        if self.memo[i as usize][j as usize].is_none() {
            let w = self.W[(i-1) as usize];  // 現在の品物の重さ
            let v = self.V[(i-1) as usize];  // 現在の品物の価値

            let mut res = self.f(i-1,j);  // 現在の品物を選ばない場合
            if w <= j {
                res = cmp::max(res, v + self.f(i-1,j-w));  // 現在の品物を選ぶ場合
            }
            self.memo[i as usize][j as usize] = Some(res);
        }
        self.memo[i as usize][j as usize].unwrap()
    }
}

fn main() {
    let mut _input = String::new();
    {
        use ::std::io::Read;
        ::std::io::stdin().read_to_string(&mut _input).unwrap();
    }
    let mut sc = Scanner::new(&_input);

    let N    = sc.value::<i64>();
    let WMAX = sc.value::<i64>();
    let mut W = Vec::with_capacity(N as usize);
    let mut V = Vec::with_capacity(N as usize);
    for _ in 0..N {
        W.push(sc.value::<i64>());
        V.push(sc.value::<i64>());
    }

    let mut sol = Solver::new(W, V);
    let ans = sol.f(N, WMAX);

    println!("{}", ans);
}
//  [swift]

/// Swift5 -> Swift2.2
extension String {
    // split(separator:maxSplits:omittingEmptySubsequences:)
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map(String.init)
    }
}
extension Array {
    // init(repeating:count:)
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
extension Array where Element: Comparable {
    // sorted()
    func sorted() -> [Element] {
        return self.sort( { $0 < $1 } )
    }
}
// stride(from:through:by:)
func stride(from start: Int, through end: Int, by stride: Int) -> StrideThrough<Int> {
    return start.stride(through: end, by: stride)
}
// stride(from:to:by)
func stride(from start: Int, to end: Int, by stride: Int) -> StrideTo<Int> {
    return start.stride(to: end, by: stride)
}
/// end

let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let W = input[1]

var dp = Array(repeating: 0, count: W + 1)

for _ in 0 ..< N {
    let knapsack = readLine()!.split(separator: " ").map { Int($0)! }
    let weight = knapsack[0]
    let value = knapsack[1]

    let tmp = Array(weight ... W)
    for i in stride(from: W, through: weight, by: -1) {
        dp[i] = max(dp[i], dp[i - weight] + value)
    }
}

print(dp.last!)
//  [swift]
/// Swift5 -> Swift2.2

extension String {
    // split(separator:maxSplits:omittingEmptySubsequences:)
    func split(separator separator: Character) -> [String] {
        return self.characters.split(separator).map(String.init)
    }
}
extension Array {
    // init(repeating:count:)
    init(repeating: Element, count: Int) {
        self.init(count: count, repeatedValue: repeating)
    }
}
extension Array where Element: Comparable {
    // sorted()
    func sorted() -> [Element] {
        return self.sort( { $0 < $1 } )
    }
}
// stride(from:through:by:)
func stride(from start: Int, through end: Int, by stride: Int) -> StrideThrough<Int> {
    return start.stride(through: end, by: stride)
}
// stride(from:to:by)
func stride(from start: Int, to end: Int, by stride: Int) -> StrideTo<Int> {
    return start.stride(to: end, by: stride)
}
extension Range {
    func reversed() -> [Element] {
        return self.reverse()
    }
}

/// end


let input = readLine()!.split(separator: " ").map { Int($0)! }
let N = input[0]
let W = input[1]

var dp = Array(repeating: 0, count: W + 1)

for _ in 0 ..< N {
    let knapsack = readLine()!.split(separator: " ").map { Int($0)! }
    let weight = knapsack[0]
    let value = knapsack[1]

    for i in stride(from: W, through: weight, by: -1) {
        dp[i] = max(dp[i], dp[i - weight] + value)
    }
}

print(dp.last!)