jiahuimbzuai/CoQuIR huggingface dataset:
//  [python]
h,n = [int(i) for i in input().split()]
ab = []
for i in range(n):
  a,b = [int(i) for i in input().split()]
  ab.append([a,b])
dp = [[float('inf')]*((h+1)+10**4) for i in range(n+1)]
dp[0][0]=0
for i in range(n):
  for j in range(h+1+10**4):
    if j>=ab[i][0]:
      dp[i+1][j]=min(dp[i][j],dp[i+1][j-ab[i][0]]+ab[i][1])
    else:
      dp[i+1][j]=dp[i][j]
      
ans = float('inf')    
for i in range(n+1):
  for j in range(h,h+1+10**4):
    ans = min(ans,dp[i][j])
print(ans)
//  [python]

H, N = list(map(int, input().split()))
ab_list = []
max_a = -float("inf")
for _ in range(N):
    a, b = list(map(int, input().split()))
    ab_list.append((a, b))
    max_a = max(max_a, a)

dp_table = [[0] + [float("inf")] * H for _ in range(N + 1)]

for i in range(1, N + 1):
    a, b = ab_list[i - 1]
    next_j = 0
    # for j in range(H + max_a):
    over_min_cost = float("inf")
    for j in range(H + 1):
        # 攻撃jをしない場合
        before_best_cost = dp_table[i - 1][j]
        dp_table[i][j] = min(dp_table[i][j], before_best_cost)
        # 攻撃jをする場合
        if j - a >= 0:
            cost = dp_table[i - 1][j - a] + b
            min_cost = min(before_best_cost, cost)

            cost = dp_table[i][j - a] + b
            min_cost = min(min_cost, cost)

            dp_table[i][j] = min(dp_table[i][j], min_cost)

        if j + a > H:
            cost = dp_table[i - 1][j] + b
            dp_table[i][H] = min(dp_table[i][H], cost)
            cost = dp_table[i][j] + b
            dp_table[i][H] = min(dp_table[i][H], cost)
            dp_table[i][H] = min(dp_table[i][H], dp_table[i - 1][H])

ans = dp_table[-1][H]
print(ans)
//  [java]
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.lang.*;


public class Main{
	public static void main(String[] args) {
		FastScanner sc = new FastScanner();
		int h = sc.nextInt();
		int n = sc.nextInt();
		int[] a = new int[n];
		int[] b = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = sc.nextInt();
			b[i] = sc.nextInt();
		}
		int[] hp = new int[h + 1];
		for (int i = 1; i <= h; i++) {
			int min = 100000000;
			for (int j = 0; j < n; j++) {
				min = Math.min(min, hp[Math.max(0, i - a[j])] + b[j]);
			}
			hp[i] = min;
		}
		System.out.println(hp[h]);
	}
	
}

class FastScanner {
	private final InputStream in = System.in;
	private final byte[] buffer = new byte[1024];
	private int ptr = 0;
	private int buflen = 0;
	private boolean hasNextByte() {
		if (ptr < buflen) {
			return true;
		} else {
			ptr = 0;
			try {
				buflen = in.read(buffer);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (buflen <= 0) {
				return false;
			}
		}
		return true;
	}
	private int readByte() {
		if (hasNextByte()) {
			return buffer[ptr++];
		} else {
			return -1;
		}
	}
	private static boolean isPrintableChar(int c) {
		return 33 <= c && c <= 126;
	}
	public boolean hasNext() {
		while (hasNextByte() && !isPrintableChar(buffer[ptr])) {
			ptr++;
		}
		return hasNextByte();
	}
	public String next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		StringBuilder sb = new StringBuilder();
		int b = readByte();
		while (isPrintableChar(b)) {
			sb.appendCodePoint(b);
			b = readByte();
		}
		return sb.toString();
	}
	public long nextLong() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}
		long n = 0;
		boolean minus = false;
		int b = readByte();
		if (b == '-') {
			minus = true;
			b = readByte();
		}
		if (b < '0' || '9' < b) {
			throw new NumberFormatException();
		}
		while (true) {
			if ('0' <= b && b <= '9') {
				n *= 10;
				n += b - '0';
			} else if (b == -1 || !isPrintableChar(b)) {
				return minus ? -n : n;
			} else {
				throw new NumberFormatException();
			}
			b = readByte();
		}
	}
	public int nextInt() {
		long nl = nextLong();
		if (nl < Integer.MIN_VALUE || Integer.MAX_VALUE < nl) {
			throw new NumberFormatException();
		}
		return (int) nl;
	}
	public double nextDouble() {
		return Double.parseDouble(next());
	}
}
//  [java]
import java.io.*;
import java.util.*;

public class Main {

    private static FastReader in = new FastReader(System.in);
    private static PrintWriter out = new PrintWriter(System.out);

    private static final long MOD = (long) 1e9 + 7;

    public static void main(String[] args) {
        solve();
        out.flush();
    }

    private static class Spell {
        private int strength;
        private int cost;

        private Spell(int strength, int cost) {
            this.strength = strength;
            this.cost = cost;
        }

        private double performance() {
            return (double) strength / (double) cost;
        }
    }

    private static void solve() {
        int h = in.nextInt();
        int n = in.nextInt();

        List<Spell> spells = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            int s = in.nextInt();
            int c = in.nextInt();
            spells.add(new Spell(s, c));
        }

        memo = new int[h + 1];
        Arrays.fill(memo, Integer.MAX_VALUE / 2);
        out.println(minCost(spells, h));
    }

    private static int[] memo;

    private static int minCost(List<Spell> spells, int hp) {
        if (hp <= 0) return 0;
        if (memo[hp] != Integer.MAX_VALUE / 2) return memo[hp];
        int min = Integer.MAX_VALUE;
        for (Spell spell : spells) {
            min = Math.min(min, spell.cost + minCost(spells, hp - spell.strength));
        }
        memo[hp] = min;
        return min;
    }

    // https://www.geeksforgeeks.org/fast-io-in-java-in-competitive-programming/
    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        FastReader(InputStream inputStream) {
            br = new BufferedReader(new
                    InputStreamReader(inputStream));
        }

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

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

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

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

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

        // https://qiita.com/masakinpo/items/5f77f2a879578a85a0bb
        public int[] nextIntArray(int n) {
            int[] a = new int[n];
            for (int i = 0; i < n; i++)
                a[i] = nextInt();
            return a;
        }

        public long[] nextLongArray(int n) {
            long[] a = new long[n];
            for (int i = 0; i < n; i++)
                a[i] = nextLong();
            return a;
        }
    }
}
//  [cpp]
//#pragma GCC optimize ("O3")
//#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int dp[10001];
int AB[10001];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int H = getint(), N = getint();
	rep1(i, 10000) dp[i] = 1e9;
	rep1(i, 10000) AB[i] = 2e9;

	rep(i, N) {
		int a = getint(), b = getint();
		chmin(AB[min(H, a)], b);
	}

	double saikou = 1e20;
	int kotae = 2e9;
	rep1(i, 10000) {
		int k = AB[i];
		if (k < 1e9) {
			int ima = k;
			for (int j = i + i; j <= 10000; j += i) {
				ima += k;
				if (AB[j] >= ima) AB[j] = 2e9;
			}
			chmin(kotae, (H + i - 1) / i * k);
			chmin(saikou, 1.0 * k / i);
		}
	}

	for (int i = 10000; i >= 1; i--) {
		int k = AB[i];
		if (k < 1e9) {
			double kouritu1 = 1.0 * k / i;
			double kouritu2 = 1.0 * kotae / H;
			double are = H * (kouritu2 - saikou) / (kouritu1 - saikou);
			if (are > i) {
				auto dp2 = dp + i;
				int kazu = max(0, H - i);
				for (int j = 0; j < kazu; j++) if (dp2[j] > dp[j] + k) dp2[j] = dp[j] + k;
				for (int j = kazu; j <= H; j++) if (kotae > dp[j] + k) kotae = dp[j] + k;
			}
		}
	}
	printf("%d", kotae);

	Would you please return 0;
}
//  [cpp]
//#pragma GCC optimize ("O3")
//#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int dp[10001];
int AB[10001];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int H = getint(), N = getint();
	rep1(i, 10000) dp[i] = 1e9;
	rep1(i, 10000) AB[i] = 2e9;

	rep(i, N) {
		int a = getint(), b = getint();
		chmin(AB[min(H, a)], b);
	}

	double saikou = 1e20;
	rep1(i, 10000) {
		int k = AB[i];
		if (k < 1e9) {
			int ima = k;
			for (int j = i + i; j <= 10000; j += i) {
				ima += k;
				if (AB[j] >= ima) AB[j] = 2e9;
			}
			chmin(saikou, 1.0 * k / i);
		}
	}

	int kotae = 2e9;
	for (int i = 10000; i >= 1; i--) {
		int k = AB[i];
		if (k < 1e9) {
			double kouritu1 = 1.0 * k / i;
			double kouritu2 = 1.0 * kotae / H;
			double are = H * (kouritu2 - saikou) / (kouritu1 - saikou);
			if (are > i) {
				auto dp2 = dp + i;
				int kazu = max(0, H - i);
				for (int j = 0; j < kazu; j++) if (dp2[j] > dp[j] + k) dp2[j] = dp[j] + k;
				for (int j = kazu; j <= H; j++) if (kotae > dp[j] + k) kotae = dp[j] + k;
			}
		}
	}
	printf("%d", kotae);

	Would you please return 0;
}
//  [cpp]
//#pragma GCC optimize ("O3")
//#pragma GCC target ("avx")
//#include<bits/stdc++.h>
#include<cstdio>
#include<algorithm>
using namespace std;
typedef long long ll;
#define rep(i, n) for(int i = 0; i < (n); i++)
#define rep1(i, n) for(int i = 1; i <= (n); i++)
#define co(x) cout << (x) << "\n"
#define cosp(x) cout << (x) << " "
#define ce(x) cerr << (x) << "\n"
#define cesp(x) cerr << (x) << " "
#define pb push_back
#define mp make_pair
#define chmin(x, y) x = min(x, y)
#define chmax(x, y) x = max(x, y)
#define Would
#define you
#define please

const int cm = 1 << 17;
char cn[cm], * ci = cn + cm, ct;
inline char getcha() {
	if (ci - cn == cm) { fread_unlocked(cn, 1, cm, stdin); ci = cn; }
	return *ci++;
}
inline int getint() {
	int A = 0;
	if (ci - cn + 16 > cm) while ((ct = getcha()) >= '0') A = A * 10 + ct - '0';
	else while ((ct = *ci++) >= '0') A = A * 10 + ct - '0';
	return A;
}

int dp[10001];
int AB[10001];
int main() {
	//cin.tie(0);
	//ios::sync_with_stdio(false);


	int H = getint(), N = getint();
	rep1(i, 10000) dp[i] = 1e9;
	rep1(i, 10000) AB[i] = 2e9;

	rep(i, N) {
		int a = getint(), b = getint();
		chmin(AB[a], b);
	}

	double saikou = 1e20;
	rep1(i, 10000) {
		int k = AB[i];
		if (k < 1e9) {
			int ima = k;
			for (int j = i + i; j <= 10000; j += i) {
				ima += k;
				if (AB[j] >= ima) AB[j] = 2e9;
			}
			chmin(saikou, 1.0 * k / i);
		}
	}

	int kotae = 2e9;
	for (int i = 10000; i >= 1; i--) {
		int k = AB[i];
		if (k < 1e9) {
			double kouritu1 = 1.0 * k / i;
			double kouritu2 = 1.0 * kotae / H;
			double are = H * (kouritu2 - saikou) / (kouritu1 - saikou);
			if (are > i) {
				auto dp2 = dp + i;
				int kazu = max(0, H - i);
				for (int j = 0; j < kazu; j++) if (dp2[j] > dp[j] + k) dp2[j] = dp[j] + k;
				for (int j = kazu; j <= H; j++) if (kotae > dp[j] + k) kotae = dp[j] + k;
			}
		}
	}
	printf("%d", kotae);

	Would you please return 0;
}
//  [cpp]
#pragma region RegionDefs
#pragma GCC optimize("Ofast")
#include <bits/stdc++.h>
#include "boost/multi_array.hpp"
#define rep(i,n) for(int i=0,i##_len=(n);i<i##_len;++i)
#define reps(i,j,n) for(int i=(j),i##_len=(n);i<i##_len;++i)
#define repr(i,n) for(int i=(n);i>=0;--i)
#define all(x) begin(x),end(x)
using namespace std;
template<class T=int> using P  = pair<T, T>;
template<class T=int> using V  = vector<T>;
template<class T=int> using PQ = priority_queue<T>;
template<class T=int> using PQG = priority_queue<T, V<T>, greater<T>>;
typedef long long ll;
const int INF = 1e9;
const ll MOD = 1000000007LL;
void in() {}
template<class Head, class... Tail>
void in(Head&& head, Tail&&... tail)
{
    cin >> head;
    in(move(tail)...);
}
#define IN(...) ll __VA_ARGS__; in(__VA_ARGS__)
//時間が厳しいとき使う
#define INI(...) int __VA_ARGS__; in(__VA_ARGS__)
#define INS(T, ...) T __VA_ARGS__; in(__VA_ARGS__)
#define VIN(T, v, n) V<T> v(n); for(auto& _elem:v)cin>>_elem
template<class T>bool chmax(T &a, const T &b) {if (a<b) {a=b; return 1;} return 0;}
template<class T>bool chmin(T &a, const T &b) {if (a>b) {a=b; return 1;} return 0;}
#define y0 y__0
#define y1 y__1
#define j0 j__0
#define j1 j__1
#pragma endregion RegionDefs

ll dp[100000];
ll a[10000];
ll b[10000];

void solve()
{
    IN(h, n);
    vector<pair<ll,ll>> p;
    rep(i, n)
    {
        cin >> a[i] >> b[i];
        p.emplace_back(b[i], a[i]);
    }
    sort(all(p));
    dp[0] = 0;
    reps(i, 1, h+1)
    {
        dp[i] = INF;
    }
    rep(i, h+1)
    {
        ll s = 1;
        rep(j, n)
        {
            reps(k, s, p[j].second+1)
            {
                chmin(dp[i+k], dp[i] + p[j].first);
            }
            s = p[j].second + 1;
        }
    }
    cout << dp[h] << endl;
}

int main()
{
    cin.tie(0); cout.tie(0);
    ios::sync_with_stdio(false);
    cout << setprecision(numeric_limits<double>::max_digits10);

    solve();

    return 0;
}
//  [cpp]
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

vector<ll> a, b;

ll ceil(ll n, ll m) {
    return n % m == 0 ? n / m : n / m + 1;
}

ll dp[1001][10001];

ll solve(ll h, ll i, ll n) {
    if (h <= 0) return 0;
    if (i == n - 1) return ceil(h, a[i]) * b[i];
    if (dp[i][h]) {
        return dp[i][h];
    }
    ll k = 0, ans = LLONG_MAX;
    ll t = ceil(h, a[i]);
    while (k <= t) {
        ans = min(ans, solve(h - k * a[i], i + 1, n) + k * b[i]);
        ++k;
    }
    dp[i][h] = ans;
    return dp[i][h];
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll h, n;
    cin >> h >> n;
    a = vector<ll>(n);
    b = vector<ll>(n);
    for (ll i = 0; i < n; i++) {
        cin >> a[i] >> b[i];
    }
    map<int,ll> mp;
    for (ll i = 0; i < n; i++) {
      if (mp.count(a[i])) {
        mp[a[i]]=min(mp[a[i]],b[i]);
      } else {
        mp[a[i]]=b[i];
      }
    }
    a.clear();
    b.clear();
    for (auto &p:mp) {
      a.push_back(p.first);
      b.push_back(p.second);
    }
    cout << solve(h, 0, a.size());
    return 0;
}
//  [cpp]
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;

ll H,N;
ll A[1000];
ll B[1000];
priority_queue<pair<ll,ll>, vector<pair<ll,ll>>, greater<pair<ll,ll>>> pq;
ll cost[10001];

int main(){
    cin >> H >> N;
    for(int i=0;i<N;i++) cin >> A[i] >> B[i];
    for(int i=0;i<=H;i++) cost[i] = 1e15;
    pq.push(make_pair(0,0));
    while(true){
        pair<ll,ll> p = pq.top();
        pq.pop();
        ll c = p.first;
        ll d = p.second;
        if(d >= H){
            cout << c << endl;
            break;
        }
        if(cost[d] != 1e15) continue;
        cost[d] = c;
        for(int i=0;i<N;i++){
            if(d+B[i] <= H && cost[d+B[i]] != 1e15) continue;
            pq.push(make_pair(c + B[i],d + A[i]));
        }
    }
    return 0;
}
//  [c]
//abc153E
#include <malloc.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
  int h, n, i, k;
  scanf("%d %d", &h, &n);
  int dp[h], a[n], b[n]; //dp:HPをh減らすために必要な最小魔力、a:AtackPoint、b:MagicPoint
  for(i=0; i < n; i++) scanf("%d %d", &a[i], &b[i]);
  for(i=0; i < h; i++) dp[i]=(1 + i / a[0]) * b[0];//1種類のみで減らしてみる

  for(i=1; i < n; i++){//種類を増やしていく
    for(k=0; k < h; k++){
      if(k < a[i]){
        if(dp[k] > b[i]) dp[k]=b[i];
      }else if(dp[k] > dp[k - a[i]] + b[i]) dp[k]=dp[k - a[i]] + b[i];
    }
  }
  printf("%d", dp[h - 1]);
}
//  [c]
//abc153E
#include <malloc.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void) {
  int h, n, i, k;
  scanf("%d %d", &h, &n);
  int dp[h], a[n], b[n];//dp:HPをh減らすために必要な最小魔力、a:AtackPoint、b:MagicPoint
  for(i=0; i < n; i++)
    scanf("%d %d", &a[i], &b[i]);

  for(i=0; i < h; i++){
    dp[i]=(1 + i / a[0]) * b[0];
    //printf("%d ", dp[i]);
  }
  //printf("\n");

  for(i=1; i < n; i++){
    for(k=0; k < h; k++){
      if(k < a[i]){
        if(dp[k] > b[i]) dp[k]=b[i];
      }else if(dp[k] > dp[k - a[i]] + b[i]) dp[k]=dp[k - a[i]] + b[i];
      //printf("%d ", dp[k]);
    }
    //printf("\n");
  }
  printf("%d", dp[h-1]);

}
//  [c]
char buf[1<<18];sz;
N,H;
dp[10000];
main()
{
	read(0,buf,1<<18);
	for(;;)
	{
		char k=buf[sz++];
		if(k<'0')break;
		H=H*10+k-'0';
	}
	for(;;)
	{
		char k=buf[sz++];
		if(k<'0')break;
		N=N*10+k-'0';
	}
	int ans=1000000000;
	for(int i=1;i<H;i++)dp[i]=1000000000;
	for(int i=0;i<N;i++)
	{
		int A=0,B=0;
		for(;;)
		{
			char k=buf[sz++];
			if(k<'0')break;
			A=A*10+k-'0';
		}
		for(;;)
		{
			char k=buf[sz++];
			if(k<'0')break;
			B=B*10+k-'0';
		}
		for(int j=0;j<H;j++)
		{
			int now=dp[j]+B;
			if(j+A<H)
			{
				if(dp[j+A]>now)dp[j+A]=now;
			}
			else
			{
				if(ans>now)ans=now;
			}
		}
	}
	printf("%d\n",ans);
}
//  [c]
#include <stdio.h>
#include <stdlib.h>
#define min(a, b) ((a) < (b) ? (a) : (b))
#define max(a, b) ((a) > (b) ? (a) : (b))
#define abs(a) ((a) > 0 ? (a) : (-1 * (a)))
#define rep(i, n) for ((i) = 0; (i) < (int)(n); (i)++)
#define rep2(i, s, e) for ((i) = (s); (i) < (int)(e); (i)++)

void arg_marge(int *, int *, int);

int main(void)
{

    int h, n, i, j;
    int *a, *a2, *b, *b2, *ab, *c;
    int *dp, *dp2;

    scanf("%d %d", &h, &n);
    a = (int *)malloc(n * sizeof(int));
    b = (int *)malloc(n * sizeof(int));
    a2 = (int *)malloc(n * sizeof(int));
    b2 = (int *)malloc(n * sizeof(int));
    ab = (int *)malloc(n * sizeof(int));
    c = (int *)malloc(n * sizeof(int));
    rep(i, n)
    {
        scanf("%d %d", a2 + i, b2 + i);
        ab[i] = (h * b2[i]) / a2[i];
        c[i] = i;
    }
    arg_marge(ab, c, n);
    rep(i, n)
    {
        a[i] = a2[c[i]];
        b[i] = b2[c[i]];
    }
    free(a2);
    free(b2);
    free(ab);
    free(c);
    int mx = ((h / a[0] + 1) * b[0]) + 1;
    dp = (int *)malloc(mx * sizeof(int));
    dp2 = (int *)malloc(mx * sizeof(int));
    rep(i, mx)
    {
        dp[i] = 0;
        dp2[i] = 0;
    }
    //rep(j, mx) printf("%d ", dp[j]);
    rep(i, n)
    {
        //printf("\n");
        rep(j, b[i]) dp2[j] = dp[j];
        rep2(j, b[i], mx)
        {
            dp2[j] = max(dp2[j - b[i]] + a[i], dp[j]);
            //if (dp2[j] >= h)
            //{
            //    printf("break\n");
            //    mx = i + 1;
            //    break;
            //}
        }
        rep(j, mx) dp[j] = dp2[j];
        //rep(j, mx) printf("%d ", dp[j]);
    }
    rep(i, mx) if (dp[i] >= h) break;
    printf("%d", i);
}

void arg_marge(int *a, int *b, int n)
{

    if (n == 1)
        return;

    int *l2, *r2, *tmp, *arg_l2, *arg_r2, *arg_tmp;
    l2 = (int *)malloc((n / 2) * sizeof(int));
    r2 = (int *)malloc((n - n / 2) * sizeof(int));
    tmp = (int *)malloc((n) * sizeof(int));
    arg_l2 = (int *)malloc((n / 2) * sizeof(int));
    arg_r2 = (int *)malloc((n - n / 2) * sizeof(int));
    arg_tmp = (int *)malloc((n) * sizeof(int));

    for (int i = 0; i < n / 2; i++)
    {
        l2[i] = a[i];
        arg_l2[i] = b[i];
    }
    for (int i = 0; i < n - n / 2; i++)
    {
        r2[i] = a[i + n / 2];
        arg_r2[i] = b[i + n / 2];
    }

    arg_marge(l2, arg_l2, n / 2);
    arg_marge(r2, arg_r2, n - n / 2);

    for (int i = 0; i < n / 2; i++)
    {
        tmp[i] = l2[i];
        arg_tmp[i] = arg_l2[i];
    }
    for (int i = n / 2; i < n; i++)
    {
        tmp[i] = r2[n - i - 1];
        arg_tmp[i] = arg_r2[n - i - 1];
    }

    int lp = 0, rp = n - 1, p = 0;
    int l3, r3;
    while (p < n)
    {
        l3 = tmp[lp];
        r3 = tmp[rp];
        if (l3 < r3)
        {
            a[p] = l3;
            b[p] = arg_tmp[lp];
            lp++;
            p++;
        }
        else
        {
            a[p] = r3;
            b[p] = arg_tmp[rp];
            rp--;
            p++;
        }
    }

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

int     H;
int     N;
int     A[1001];
int     B[1001];

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

int             culc_answer(int dp[10001])
{
        int     i;
        int     j;

        for (i = 0; i < 100000001; i++)
        {
                if (dp[i % 10000] >= H)
                        break ;
                for (j = 0; j < N; j++)
                {
                        if (i + B[j] < 100000001)
                                dp[(i + B[j]) % 10000] = max(dp[(i  + B[j]) % 10000], dp[i % 10000] + A[j]);
                }
        }
        return (i);
}

int             main(void)
{
        int     i;
        int     answer;
        int     dp[10001] = {0};

        scanf("%d%d", &H, &N);
        for (i = 0; i < N; i++)
        {
                scanf("%d%d", &A[i], &B[i]);
        }
        answer = culc_answer(dp);
        printf("%d\n", answer);
        return (0);
}
//  [c]
#include<stdio.h>
int min(int a, int b){
  if(a<b) return a;
  else return b;
}
int main(){
  int i,j,n,m;
  int M=100000;
  int d[100010]={};
  
  for(i=1;i<M;i++)
    d[i]=1e9;
  
  scanf("%d %d",&n,&m);

  int a[m], b[m];
  for(i=0;i<m;i++){
    scanf("%d %d",&a[i],&b[i]);
  }

  for(i=0;i<m;i++){
    for(j=0;j<n;j++)d[j+a[i]]=min(d[j+a[i]],d[j]+b[i]);
    for(j=M-2;j;j--)d[j]=min(d[j],d[j+1]);
  }

  printf("%d",d[n]);
  return 0;
}
//  [javascript]
function Main(input) {
  input = input.trim().split('\n');
  H = Number(input[0].split(' ')[0]);
  M = input.slice(1).map(v => v.split(' ').map(Number));

  dp = Array(H + 1).fill(Infinity);
  dp[0] = 0;
  M.forEach(item => {
    for (i = 0; i <= H; i=(i+1)|0) {
      targetPointIndex = Math.min(i + item[0], H);
      dp[targetPointIndex] = Math.min(dp[targetPointIndex], dp[i] + item[1]);
    }
  });
  console.log(dp[H]);
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]

function Main(input) {
  input=input.split("\n");
  if(input[input.length-1]===''){
    input.pop();
  }
  const H=input[0].split(' ')[0]-0;
  const N=input[0].split(' ')[1]-0;
  var memo=[0];
  var A=input.map(e=>{
    return e.split(' ')[0]-0;
  });
  A.shift();
  var B=input.map(e=>{
    return e.split(' ')[1]-0;
  });
  B.shift();
  var min;
  for(var i=1;i<=H;i++){
    min=Infinity;
    for(var j=0;j<N;j++){
      if(i<=A[j]){
        min=Math.min(min,B[j]);
      }else{
        min=Math.min(min,B[j]+memo[i-A[j]]);
      }
    }
    memo.push(min);
  }
  console.log(memo[H]);
}


//*この行以降は編集しないでください（標準入出力から一度に読み込み、Mainを呼び出します）
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
"use strict";
var GET=(function(){function f(s){return new g(s);}function g(s){this._s=s.trim().split("\n");this._y=0;}g.prototype.a=function(f){var s=this._s, y=this._y, r;if(typeof s[y]==="string")s[y]=s[y].split(" ").reverse();r=s[y].pop();if(!s[y].length)this._y++;return f?r:+r;};g.prototype.l=function(f){var s=this._s[this._y++].split(" ");return f?s:s.map(a=>+a);};g.prototype.m=function(n,f){var r=this._s.slice(this._y,this._y+=n).map(a=>a.split(" "));return f?r:r.map(a=>a.map(a=>+a));};g.prototype.r=function(n,f){var r=this._s.slice(this._y,this._y+=n);return f?r:r.map(a=>+a);};return f;})();
var o=GET(require("fs").readFileSync("/dev/stdin","utf8"));
function xArray(v){var a=arguments,l=a.length,r="Array(a["+--l+"]).fill(0).map(x=>{return "+v+";})";while(--l)r="Array(a["+l+"]).fill(0).map(x=>"+r+")";return eval(r);}

var myOut = main();
if(myOut !== undefined)console.log(myOut);
function main(){
  var h = o.a();
  var n = o.a();
  var a = o.m(n);
  var dp = xArray(1e9,2e4+1);
  dp[0] = 0;
  for(var i = 0; i < n; i++){
    for(var j = 0; j < h; j++){
      if(dp[j]+a[i][1] < dp[j+a[i][0]])dp[j+a[i][0]] = dp[j]+a[i][1];
    }
  }
  var ans = 1e9;
  for(var i = h; i <= h+1e4; i++)if(dp[i] < ans)ans = dp[i];
  return ans;
}
//  [javascript]
'use strict'

function Main(input) {
  input = input.trim().split('\n')
  const array = input[0].split(' ').map(s => parseInt(s))
  const rest = input.slice(1)
  const H = array[0]
  const N = array[1]

  const magic = []
  for(let i = 0; i < rest.length; ++i) {
    const a = rest[i].split(' ').map(s => parseInt(s))
    magic.push([a[0], a[1]])
  }
  magic.sort((a, b) => a[0] - b[0])

  let dp = Array(H+1).fill(Infinity)

  dp[0] = 0
  for(let i = 0; i < N; ++i) {
    const w = magic[i][0]
    const v = magic[i][1]
    for(let j = 0; j <= H; ++j) {
      
      const min = Math.min(j + w, H)

      dp[min] = Math.min(dp[min], dp[j] + v) 
    }

    // console.log(`${i}までの魔法を利用`)
    // console.log(dp)
    // console.log('^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^')
  }
  
  console.log(dp[H])
  
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));
//  [javascript]
function main(input) {
  var H = input[0].split(" ")[0]-0;
  var N = input[0].split(" ")[1]-0;
  var list = [];
  for(var i=1;i<=N;i++){
    list.push(input[i].split(" ").map(v=>v-0));
  }
  var dp = [0];
  var ans = Number.MAX_VALUE;
  for(var i=1;i<=H;i++){
    var min_mana = Number.MAX_VALUE;
    for(var j=0;j<N;j++){
      var a = list[j][0]; // power 
      var b = list[j][1]; // nama
      if(dp[i-a]){
        min_mana = Math.min(min_mana, dp[i-a] + b);
      }else{
        if(i<=a){
          min_mana = Math.min(min_mana, b);
        }
      }
    }
    dp[i] = min_mana;
  }
  console.log(dp[H]);
}

main(require('fs').readFileSync('/dev/stdin', 'utf8').split("\n"))
//  [javascript]
//Don't have to see. start------------------------------------------
var read = require('readline').createInterface({
  input: process.stdin, output: process.stdout
});
var obj; var inLine = [];
read.on('line', function(input){inLine.push(input);});
read.on('close', function(){
  obj = init(inLine);
  console.error('\n↑入力 ↓出力');
  Main();
});
function makeClone(obj){return (obj instanceof Set) ? new Set(Array.from(obj)) : JSON.parse(JSON.stringify(obj));}
function nextInt(){return myconv(next(),1);} function nextStrArray(){return myconv(next(),2);}
function nextIntArray(){return myconv(next(),4);} function nextCharArray(){return myconv(next(),6);}
function next(){return obj.next();} function hasNext(){return obj.hasNext();}
function init(input){  
  return {
    list : input, index : 0, max : input.length,
    hasNext : function(){return (this.index < this.max);},
    next : function(){if(this.hasNext()){return this.list[this.index++];}else{throw 'ArrayIndexOutOfBoundsException ‚There is no more input';}}
  };
}
function myout(s){console.log(s);}
function myerr(s){console.error('debug:' + require('util').inspect(s,false,null));}
//param "no" is
//unknown or outlier : return i. 1: parseInt.
//2: split space. 4: split space and parseInt.
//6: split 1 character. 7: split 1 character and parseInt.
//8: join space. 9: join nextline. 0: join no character.
function myconv(i,no){try{switch(no){case 1:return parseInt(i);case 2:return i.split(' ');case 4:return i.split(' ').map(Number);case 6:return i.split('');case 7:return i.split('').map(Number);case 8:return i.join(' ');case 9:return i.join('\n');case 0:return i.join('');default:return i;}}catch(e){return i;}}

//Don't have to see. end------------------------------------------
function Main(){
  var one = nextIntArray();
  var H = one[0];
  var N = one[1];
  var maxIndex = 11007;
  var max = 1000000000;
  var dp = new Array(maxIndex);
  dp[0] = 0;
  for(var i = 0; i < N; i++){
    var tmp = nextIntArray();
    var Ai = tmp[0];
    var Bi = tmp[1];
    for(var j = 0; j < maxIndex; j++){
      if(dp[j] != null){
        if(dp[j + Ai] == null){
          dp[j + Ai] = dp[j] + Bi;
        }else{
          dp[j + Ai] = Math.min(dp[j + Ai], dp[j] + Bi);
        }
      }
    }
  }
  dp[maxIndex - 1] = max;
  for(var i = maxIndex - 2; i >= 0; i--){
    if(dp[i] == null){
      dp[i] = dp[i + 1];
    }else{
      dp[i] = Math.min(dp[i + 1], dp[i]);
    }

  }
  myout(dp[H]);
}
//  [go]
package main

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

var scanner = bufio.NewScanner(os.Stdin)

func scanInt() int {
	scanner.Scan()
	a, err := strconv.Atoi(scanner.Text())
	if err != nil {
		fmt.Println(err)
	}
	return a
}

func main() {
	scanner.Split(bufio.ScanWords)

	h := scanInt()
	n := scanInt()

	a := make([]int, n)
	b := make([]int, n)
	for i := 0; i < n; i++ {
		a[i] = scanInt()
		b[i] = scanInt()
	}

	dp := make([]int, h+1)
	dp[0] = 0

	for i := 1; i <= h; i++ {
		min := math.MaxInt32
		for j := 0; j < n; j++ {
			if a[j] <= i {
				v := b[j] + dp[i-a[j]]
				if v < min {
					min = v
				}
			} else {
				if b[j] < min {
					min = b[j]
				}
			}
		}
		dp[i] = min
	}
	fmt.Println(dp[h])
}
//  [go]
package main

import (
	"fmt"
	"math"
)

func main() {
	var h, n int

	fmt.Scan(&h, &n)
	res := make([]int, h+1)
	for k := 0; k <= h; k++ {
		res[k] = math.MaxInt64
	}

	for i := 0; i < n; i++ {
		var HP, MP int
		fmt.Scan(&HP, &MP)
		for k := 1; k <= h; k++ {
			if k <= HP {
				if res[k] > MP {
					res[k] = MP
				}
			} else {
				use := res[k-HP] + MP
				if res[k] > use {
					res[k] = use
				}
			}
		}
	}
	fmt.Println(res[h])
}
//  [go]
package main

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

func main() {
	H := readInt()
	N := readInt()

	dp := make([]int, H+1)
	fill(dp, math.MaxInt64)

	dp[0] = 0
	for i := 0; i < N; i++ {
		A := readInt()
		B := readInt()
		for j := 0; j < H; j++ {
			if dp[j] == math.MaxInt64 {
				continue
			}
			t := min(j+A, H)
			if dp[j]+B < dp[t] {
				dp[t] = dp[j] + B
			}
		}
	}

	fmt.Println(dp[H])
}

const (
	ioBufferSize = 1 * 1024 * 1024 // 1 MB
)

var stdinScanner = func() *bufio.Scanner {
	result := bufio.NewScanner(os.Stdin)
	result.Buffer(make([]byte, ioBufferSize), ioBufferSize)
	result.Split(bufio.ScanWords)
	return result
}()

func readString() string {
	stdinScanner.Scan()
	return stdinScanner.Text()
}

func readInt() int {
	result, err := strconv.Atoi(readString())
	if err != nil {
		panic(err)
	}
	return result
}

func fill(a []int, x int) {
	for i := 0; i < len(a); i++ {
		a[i] = x
	}
}

func min(x, y int) int {
	if x < y {
		return x
	}
	return y
}
//  [go]
package main

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

func nextInt(sc *bufio.Scanner) int {
	sc.Scan()
	t, _ := strconv.Atoi(sc.Text())
	return t
}

func main() {
	sc := bufio.NewScanner(os.Stdin)
	sc.Split(bufio.ScanWords)
	H := nextInt(sc)
	N := nextInt(sc)
	M := make(map[int]int, 0)
	for i := 0; i < N; i++ {
		a := nextInt(sc)
		b := nextInt(sc)
		if M[a] == 0 {
			M[a] = b
		} else {
			M[a] = min(M[a], b)
		}
	}
	dp := make([]int, 2*int(1e4)+10)
	for i := 0; i < len(dp); i++ {
		dp[i] = int(1e9)
	}
	dp[0] = 0
	for i := 0; i < len(dp); i++ {
		for damage, cost := range M {
			if i-damage >= 0 {
				dp[i] = min(dp[i], dp[i-damage]+cost)
			}
		}
	}
	ans := int(1e9)
	for i := H; i < len(dp); i++ {
		ans = min(ans, dp[i])
	}
	fmt.Println(ans)
}
func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}
//  [go]
package main

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

func exec(stdin *Stdin, stdout *Stdout) {
	h := stdin.ReadInt()
	n := stdin.ReadInt()
	a := []int{}
	b := []int{}
	for i := 0; i < n; i++ {
		a = append(a, stdin.ReadInt())
		b = append(b, stdin.ReadInt())
	}

	dp := [][]int{}
	inf := int(math.MaxInt32)
	for i := 0; i < n+1; i++ {
		row := []int{}
		for j := 0; j < h+1; j++ {
			row = append(row, inf)
		}
		row[0] = 0
		dp = append(dp, row)
	}

	for i := 0; i < n; i++ {
		for j := 0; j < h+1; j++ {
			dp[i+1][j] = Min(dp[i+1][j], dp[i][j])
			dp[i+1][Min(h, j+a[i])] = Min(dp[i+1][Min(h, j+a[i])], dp[i+1][j]+b[i])
		}
	}
	stdout.Println(dp[n][h])
}

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

func main() {
	stdout := NewStdout()
	defer stdout.Flush()
	exec(NewStdin(bufio.ScanWords), stdout)
}

type Stdin struct {
	stdin *bufio.Scanner
}

func NewStdin(split bufio.SplitFunc) *Stdin {
	s := Stdin{bufio.NewScanner(os.Stdin)}
	s.stdin.Split(split)
	s.stdin.Buffer(make([]byte, bufio.MaxScanTokenSize), int(math.MaxInt32))
	return &s
}

func (s *Stdin) Read() string {
	s.stdin.Scan()
	return s.stdin.Text()
}

func (s *Stdin) ReadInt() int {
	n, _ := strconv.Atoi(s.Read())
	return n
}

func (s *Stdin) ReadFloat64() float64 {
	n, _ := strconv.ParseFloat(s.Read(), 64)
	return n
}

type Stdout struct {
	stdout *bufio.Writer
}

func NewStdout() *Stdout {
	return &Stdout{bufio.NewWriter(os.Stdout)}
}

func (s *Stdout) Flush() {
	s.stdout.Flush()
}

func (s *Stdout) Println(a ...interface{}) {
	fmt.Fprintln(s.stdout, a...)
}
//  [ruby]
h, n = gets.to_s.split.map{|t|t.to_i}
m = Array.new(n){ gets.split.map{|t|t.to_i} }.sort_by{|(a,b)| 1.0 * b / a }

inf = h * (10**4)

dp = [ inf ] * ( h + 1 + 10**4 )
dp[0] = 0

m.each do |(a, b)|
  0.upto(h).each do |i|
    dp[i+a] = dp[i] + b if dp[i] < inf && dp[i+a] > dp[i] + b
  end
  break if dp[h] < inf
end
# p dp
puts dp[h .. -1].min
//  [ruby]
H, N = gets.split.map(&:to_i)
ABs = readlines.map{|l| l.split.map(&:to_i)}
INF = 1<<30

dp = Array.new(H + ABs.map(&:first).max + 1, INF)
dp[0] = 0
mi = ->(x, y){x < y ? x : y}
ABs.sort_by{|a, b| b.to_f/a}.each do |a, b|
  H.times{|i| dp[i + a] = mi[dp[i + a], dp[i] + b] unless dp[i] == INF}
  break if dp[H] != INF
end
puts dp[H .. -1].min
//  [ruby]
#https://atcoder.jp/contests/abc153/submissions/9769348
#https://atcoder.jp/contests/abc153/submissions/9792185
def min(a, b)
  a < b ? a : b
end
INF = 1 << 30
H, N = gets.split.map(&:to_i)
AB = N.times.map{gets.split.map(&:to_i)}.sort{|a,b|a[0]<=>b[0]}

dp = Array.new(H + AB.last[0] + 1, INF)
AB.sort_by!{|a,b| b.to_f/a }
dp[0] = 0
AB.each do |hp, mp|
  H.times do |i|
    next if dp[i] == INF
    ni = i + hp
    dp[ni] = min(dp[ni], dp[i] + mp) 
  end
  break if dp[H] < INF
end
puts dp[H..-1].min
//  [ruby]
def main
  h, n = gets.chomp.split.map(&:to_i)
  m = []
  n.times do |i|
  	m.push(gets.chomp.split.map(&:to_i))
  end
  
  #DPを使ってO(h * n) で解く
  dp = Array.new(h, 1000000000)
  
  h.times do |i|
    n.times do |j|
      #k = m[i][0]個前の最小値
      if i < m[j][0]
        k = m[j][1]
      else
        k = dp[i - m[j][0]] + m[j][1]
      end
      
      if dp[i] > k
        dp[i] = k
      end
    end
  end
  
  puts dp[-1]
end
 
main
//  [ruby]
# 解説AC(できるといいな)
h, n = gets.split.map(&:to_i)
magic = n.times.map{gets.split.map(&:to_i)}
a_max = magic.max{|e1, e2| e1[0] <=> e2[0]}[0]
dp = Array.new(h + a_max * 2, 0)
for dm in 1...(h + a_max) do
  dp[dm + a_max] = magic.map{|mg| dp[dm + a_max - mg[0]] + mg[1]}.min
end
puts dp.slice(h + a_max, a_max).min
//  [ruby]
h, n = gets.split.map(&:to_i)
min_of = [0] * (h + 1)

magics = n.times.map{|i|
    gets.split.map(&:to_i)
}
(h + 1).times{|hp|
    min_of[hp] = magics.map{|m|
        if hp <= m[0]
            m[1]
        else
            min_of[hp - m[0]] + m[1]
        end
    }.min
}
puts min_of[h]
//  [rust]
use std::io::Read;
use std::cmp::Ordering;

#[derive(Eq,PartialEq)]
struct Magic {
    atk: usize,
    mp: usize,
}

impl Ord for Magic {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

impl PartialOrd for Magic {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self.atk as f64 / self.mp as f64).partial_cmp(&(other.atk as f64 / other.mp as f64)) {
            Some(Ordering::Greater) => Some(Ordering::Less),
            Some(Ordering::Less) => Some(Ordering::Greater),
            _ => Some(self.atk.cmp(&other.atk)),
        }
    }
}

fn main() {
    let mut buf = String::new();
    let stdin = std::io::stdin();
    stdin.lock().read_to_string(&mut buf).unwrap();
    let mut iter = buf.split_whitespace();
    let hp = iter.next().unwrap().parse::<usize>().unwrap();
    let n = iter.next().unwrap().parse::<usize>().unwrap();

    let mut magics: Vec<Magic> = Vec::with_capacity(n);
    for _ in 0..n {
        let a = iter.next().unwrap().parse::<usize>().unwrap();
        let b = iter.next().unwrap().parse::<usize>().unwrap();
        magics.push( Magic { atk: a, mp: b } );
    }

    magics.sort();

    // dp[hp] min_mp
    let mut dp: Vec<usize> = vec![0; hp+1];
    for i in 1..hp+1 {
        let mut min_mp = std::usize::MAX;
        for m in &magics {
            let consume_mp = if i > m.atk { dp[i-m.atk] + m.mp } else { m.mp };
            min_mp = std::cmp::min(consume_mp, min_mp);
        }
        dp[i] = min_mp;
    }

    println!("{}", dp[hp]);
}
//  [rust]
use std::io;
fn main() {
    let (h, waza) = {
        let mut i = String::new();
        io::stdin().read_line(&mut i).unwrap();
        let mut it = i.split_whitespace();
        let (h, n): (usize, usize) = {
            (
                it.next().unwrap().parse().unwrap(),
                it.next().unwrap().parse().unwrap(),
            )
        };
        let mut waza: Vec<(usize, usize)> = Vec::new();
        for _ in 0..n {
            let mut i = String::new();
            io::stdin().read_line(&mut i).unwrap();
            let mut it = i.split_whitespace();
            waza.push((
                it.next().unwrap().parse().unwrap(),
                it.next().unwrap().parse().unwrap(),
            ))
        }
        (h, waza)
    };
    /*
    println!("{}", h);
    for i in waza {
        println!("{},{}", i.0, i.1);
    }
    */
    let mut dp: Vec<usize> = Vec::new();
    dp.push(0);
    for i in 1..h + 1 {
        //println!("dp[{}] start", i);
        let mut min_mp = std::usize::MAX;
        for m in &waza {
            //println!("compare atk:{},mp:{}", m.1, m.0);
            let tmp_mp = if i > m.0 { dp[i - m.0] + m.1 } else { m.1 };
            //println!("tmp_mp is {}", tmp_mp);
            min_mp = std::cmp::min(min_mp, tmp_mp);
        }
        //println!("min_mp is {}", min_mp);
        dp.push(min_mp);
    }
    println!("{}", dp[h]);
}
//  [rust]
fn read<T: std::str::FromStr>(
    stdin_lock: &mut std::io::StdinLock,
    buf: &mut Vec<u8>,
    delimiter: u8,
) -> T {
    buf.clear();
    let l = std::io::BufRead::read_until(stdin_lock, delimiter, buf).unwrap();
    buf.truncate(l - 1); // remove delimiter
    let s = unsafe { std::str::from_utf8_unchecked(&buf) };
    s.parse().unwrap_or_else(|_| panic!("read"))
}

fn main() {
    use std::cmp::min;

    let stdin = std::io::stdin();
    let mut stdin_lock = stdin.lock();
    let mut buf: Vec<u8> = Vec::new();

    // input
    let h: usize = read(&mut stdin_lock, &mut buf, b' ');
    let n: usize = read(&mut stdin_lock, &mut buf, b'\n');
    let mut abv = vec![(0usize, 0usize); n];
    for i in 0..n {
        abv[i].0 = read(&mut stdin_lock, &mut buf, b' ');
        abv[i].1 = read(&mut stdin_lock, &mut buf, b'\n');
    }

    abv.sort();

    // 体力減少が x 以上のうち最も魔力の消耗が少ないものを選ぶ
    let mut tbl = vec![0usize; h + 1]; // tbl[hp] = min_mp;
    for i in 1..h + 1 {
        let mut min_mp = usize::max_value();
        for j in 0..n {
            let (a, b) = abv[j];
            min_mp = min(min_mp, if i > a { tbl[i - a] + b } else { b });
        }
        tbl[i] = min_mp;
    }

    println!("{}", tbl[h]);
}
//  [rust]
// 標準入力から一行を読み取り、指定の型に変換する
fn read<T: std::str::FromStr>() -> T {
    let mut s = String::new();
    std::io::stdin().read_line(&mut s).ok();
    s.trim().parse().ok().unwrap()
}

// 標準入力から一行を読み取り、空白文字で分割し、各要素を指定の型に変換する関数
fn read_vec<T: std::str::FromStr>() -> Vec<T> {
    read::<String>().split_whitespace()
        .map(|e| e.parse().ok().unwrap()).collect()
}

// 標準入力からn行を読み取り、各行を空白文字で分割し、各要素を指定の型に変換する関数
fn read_vec2<T: std::str::FromStr>(n: u32) -> Vec<Vec<T>> {
    (0..n).map(|_| read_vec()).collect()
}

use std::cmp::*;

fn main() {
    let hn: Vec<i64> = read_vec();
    let abi: Vec<Vec<i64>> = read_vec2(hn[1] as u32);

    let h = hn[0];
    let max_cost = 10000 * 10000 as usize + 1;

    // 添字...消費コスト 値...与ダメージ
    let mut dp = vec![0_u64; max_cost];
    for i in 1..max_cost as usize {
        for j in 0..hn[1] as usize {
            if abi[j][1] > i as i64 { continue; }
            let short: usize = i - abi[j][1] as usize;
            dp[i] = max(dp[i], abi[j][0] as u64 + dp[short]);
        }

        if dp[i] >= h as u64 { println!("{}", i); return; }
    }
}
//  [swift]
let input = readLine()!.split(separator: " ").map { Int($0)! }
let H = input[0]
let N = input[1]
var A: [Int] = .init(repeating: 0, count: N)
var B: [Int] = .init(repeating: 0, count: N)

for i in 0..<N {
  let tmp = readLine()!.split(separator: " ").map { Int($0)! }
  A[i] = tmp[0]
  B[i] = tmp[1]
}

var dp: [Int] = .init(repeating: Int.max, count: H + 1)
dp[0] = 0

for i in 1...H {
  for j in 0..<A.count {
    let offset = i - A[j] >= 0 ? dp[i - A[j]] : 0
    dp[i] = min(dp[i], B[j] + offset)
  }
}
print(dp[H])
//  [typescript]
{
  const main = (
    input: string
  ): void | string | number | string[] | number[] => {
    const r = _reader(input)
    const [H, N] = r.nn()
    const A: { cost: number; power: number }[] = []

    const dp: number[] = []

    dp[0] = 0

    for (let i = 0; i < N; i++) {
      const [power, cost] = r.nn()

      A.push({ power, cost })
    }

    A.sort((a, b) => b.power / b.cost - a.power / a.cost)

    let min = Infinity

    // console.log(A)

    A.forEach(({ power, cost }) => {
      for (let i = 0; i < H; i++) {
        if (dp[i] === undefined) continue
        const newCost = dp[i] + cost

        if (i + power >= H) {
          min = Math.min(min, newCost)
          return
        }
        if (dp[i + power] === undefined) {
          dp[i + power] = newCost
        }
        dp[i + power] = Math.min(dp[i + power], newCost)
        // console.log(dp[i])
        // console.log(cost)
        // console.log(dp[i] + cost)
      }
    })
    // console.log(dp)

    return min
  }

  const _reader = (str: string, i = 0) => {
    const lines = str.trim().split('\n')
    const s = () => lines[i++] || ''
    const n = () => Number(s())

    const mn = (v: string[]) => v.map(Number)
    const sp = (v: string) => v.split(' ')
    const ss = () => sp(s())
    const nn = () => mn(ss())
    const nls = () => mn(lines.slice(i))
    const nnls = () => lines.slice(i).map(v => mn(sp(v)))

    return { lines, s, n, ss, nn, nls, nnls }
  }

  const _getInput = () => require('fs').readFileSync('/dev/stdin', 'utf8')
  const _res = main(_getInput())

  if (typeof _res === 'number' || typeof _res === 'string') console.log(_res)
  if (typeof _res === 'object') console.log(_res.join(' '))
}
//  [typescript]
'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
	//const H=p[0];
	//const N=p[1];
	//const N = parseInt(p[0]);//N
    const H = parseInt(p[0].split(" ")[0]);//N M
	const N = parseInt(p[0].split(" ")[1]);//N M
	//let h = (p[1].split(" ").map(Number));//a1 a2 a3...
	let A=new Array(N+10);
	let B=new Array(N+10);
	let w = new Array(N+10);
	for(let i=1;i<=N;i++){
	    let t=p[i].split(" ").map(Number);
	    A[i]=t[0];
	    B[i]=t[1];
	    w[i]=new Array(H).fill(Infinity);
	}
	for(let i=1;i<=H;i++)w[1][i]=Math.ceil(i/A[1])*B[1];
    
    for(let i=2;i<=N;i++){
	    for(let j=1;j<=H;j++){
	        let mp=Math.ceil(j/A[i])*B[i];
	        w[i][j]=Math.min(w[i-1][j],mp);
	        if(j>A[i]){
	            w[i][j]=Math.min(w[i][j],w[i][j-A[i]]+B[i]/*dam*/);
	        }
	    }   
	}
	console.log(w[N][H])
}
Main(require("fs").readFileSync("/dev/stdin", "utf8").trim());
//  [python]
S = input()
array = []
for w in S:
    if w == "B" and len(array):
        array.pop()
    elif w != "B":
        array.append(w)
for w in array:
    print(w, end="")
print()
//  [python]
s=str(input())
while "B" in s:
  if s[0] == "B":
    s=s[1:]
  s=s.replace("0B","")
  s=s.replace("1B","")
print(s)
//  [python]
res = []
s = input()
for c in s:
    if c=='B':
        if len(res)!=0:
            res = res[:-1]
    else:
        res.append(c)
print(''.join(res))
//  [python]
import re
import doctest

class IO_for_Contest(object):
    @staticmethod
    def my_input():
        #return raw_input()
        return input()

    @staticmethod
    def read_from_input():
        #TODO: impl this for each problem
        pass

    @staticmethod
    def read_line():
        return IO_for_Contest.my_input().strip()

    @staticmethod
    def read_int():
        return int(IO_for_Contest.my_input().strip())

    @staticmethod
    def read_n_int(n):
        return list(map( \
                int, \
                re.split('\s+', IO_for_Contest.my_input().strip())))[ : n]
def solve():
    l = []
    buf = IO_for_Contest.read_line()
    for x in buf:
        if x == 'B':
            if len(l) > 0:
                l.pop()
        else:
            l.append(x)
    print(''.join(l))

if __name__ == '__main__':
    #doctest.testmod()
    solve()
//  [python]
# -*- coding: utf-8 -*-
 
## Library
 
import sys
from fractions import gcd
import math
from math import ceil,floor
import collections
from collections import Counter
import itertools
import copy
 
## input
 
# N=int(input())
# A,B,C,D=map(int, input().split())
# S = input()
# yoko = list(map(int, input().split()))
# tate = [int(input()) for _ in range(N)]
# N, M = map(int,input().split()) 
#    P = [list(map(int,input().split())) for i in range(M)]
#    S = []
#    for _ in range(N):
#        S.append(list(input()))
 
S = input()

ans = []

for i in range(len(S)):
    if S[i] == "0" or S[i] == "1":
        ans.append(S[i])
    elif 0 < len(ans):
        ans.pop()

for i in range(len(ans)):
    print(ans[i], end='')
//  [python]
S = input()
ans = []
for x in S:
    if (x == '0'):
        ans.append('0')
    elif (x == '1'):
        ans.append('1')
    else:
        if (len(ans) > 0):
            ans.pop()
ans = "".join(ans)
print (ans)
//  [java]
import java.io.BufferedReader;
import java.io.InputStreamReader;

class Main {
  public static void main(String[] args) throws Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      char[] cl = br.readLine().toCharArray();
      StringBuffer sb = new StringBuffer("");
      for (char c : cl){
        if (c == '0' || c == '1' ) {
          sb.append(c);
        } else {
          if(!sb.toString().isEmpty()){
            sb.delete(sb.toString().length() - 1,sb.toString().length());
          }
        }
      }
      System.out.println(sb.toString());
  }
}