Problem:
Score : 300 points

Problem Statement

Hearing that energy drinks increase rating in those sites, Takahashi decides to buy up M cans of energy drinks.

There are N stores that sell energy drinks. In the i-th store, he can buy at most B_i cans of energy drinks for A_i yen (the currency of Japan) each.

What is the minimum amount of money with which he can buy M cans of energy drinks?

It is guaranteed that, in the given inputs, a sufficient amount of money can always buy M cans of energy drinks.

Constraints

All values in input are integers.

1 \leq N, M \leq 10^5

1 \leq A_i \leq 10^9

1 \leq B_i \leq 10^5

B_1 + ... + B_N \geq M

Input

Input is given from Standard Input in the following format:

N M
A_1 B_1
A_2 B_2
\vdots
A_N B_N

Output

Print the minimum amount of money with which Takahashi can buy M cans of energy drinks.

Sample Input 1

2 5
4 9
2 4

Sample Output 1

12

With 12 yen, we can buy one drink at the first store and four drinks at the second store, for the total of five drinks. However, we cannot buy 5 drinks with 11 yen or less.

Sample Input 2

4 30
6 18
2 5
3 10
7 9

Sample Output 2

130

Sample Input 3

1 100000
1000000000 100000

Sample Output 3

100000000000000

The output may not fit into a 32-bit integer type.

Solution in Rust (1.15.1) (judge verdict: Accepted)

use std::io::*;
use std::str::FromStr;
use std::collections::HashMap;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::collections::HashSet;
use std::cmp;
use std::f64::consts;
use std::cmp::Ordering;
use std::collections::VecDeque; //push_back, pop_front
use std::collections::BinaryHeap;
use std::usize;

const MOD: i64 = 1000000007;

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

    let mut vec: Vec<(i64, i64)> = Vec::new();
    for i in 0..n {
        let a: i64 = read();
        let b: i64 = read();

        vec.push((a, b));
    }

    vec.sort_by_key(|k| k.0);

    let mut count = 0;
    let mut money = 0;

    for &t in vec.iter() {
        let a = t.0;
        let mut b = t.1;

        if count+b >= m {
            loop {
                b-=1;
                if count+b < m {
                    money += a*(b+1);
                    count+=(b+1);
                    break;
                }
            }
            break;
        } else {
            money += a*b;
            count += b;
        }
    }

    println!("{}", money);
}


#[derive(Copy, Clone, Eq, PartialEq)]
struct State {
    cost: usize,
    position: usize,
}

// The priority queue depends on `Ord`.
// Explicitly implement the trait so the queue becomes a min-heap
// instead of a max-heap.
impl Ord for State {
    fn cmp(&self, other: &State) -> Ordering {
        // Notice that the we flip the ordering on costs.
        // In case of a tie we compare positions - this step is necessary
        // to make implementations of `PartialEq` and `Ord` consistent.
//        other.cost.cmp(&self.cost)
//            .then_with(|| self.position.cmp(&other.position))

        let c = other.cost.cmp(&self.cost);
        if c != Ordering::Equal {
            c
        } else {
            self.position.cmp(&other.position)
        }
    }
}

// `PartialOrd` needs to be implemented as well.
impl PartialOrd for State {
    fn partial_cmp(&self, other: &State) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

// Each node is represented as an `usize`, for a shorter implementation.
#[derive(Debug, Clone)]
struct Edge {
    node: usize,
    cost: usize,
}

// Dijkstra's shortest path algorithm.

// Start at `start` and use `dist` to track the current shortest distance
// to each node. This implementation isn't memory-efficient as it may leave duplicate
// nodes in the queue. It also uses `usize::MAX` as a sentinel value,
// for a simpler implementation.
fn shortest_path(adj_list: &Vec<Vec<Edge>>, start: usize, goal: usize) -> Option<usize> {
    // dist[node] = current shortest distance from `start` to `node`
    let mut dist: Vec<_> = (0..adj_list.len()).map(|_| usize::MAX).collect();

    let mut heap = BinaryHeap::new();

    // We're at `start`, with a zero cost
    dist[start] = 0;
    heap.push(State { cost: 0, position: start });

    // Examine the frontier with lower cost nodes first (min-heap)
    while let Some(State { cost, position }) = heap.pop() {
        // Alternatively we could have continued to find all shortest paths
        if position == goal { return Some(cost); }

        // Important as we may have already found a better way
        if cost > dist[position] { continue; }

        // For each node we can reach, see if we can find a way with
        // a lower cost going through this node
        for edge in &adj_list[position] {
            let next = State { cost: cost + edge.cost, position: edge.node };

            // If so, add it to the frontier and continue
            if next.cost < dist[next.position] {
                heap.push(next);
                // Relaxation, we have now found a better way
                dist[next.position] = next.cost;
            }
        }
    }

    // Goal not reachable
    None
}

//(フェルマーの定理)
// (ab / a / b) % MOD を計算したいので、
// (ab * calc(a, MOD-2, MOD) % MOD * calc(b, MOD-2, MOD) % MOD を計算する。
fn calc(a: i64, b: i64, p: i64) -> i64 {
    if b == 0 {
        return 1;
    }
    if b % 2 == 0 {
        let d = calc(a, b/2, p);
        return (d * d) % p;
    } else {
        return (a * calc(a, b-1, p)) % p;
    }
}

// 素因数分解
fn prime_factorization(number: u64) -> Vec<u64> {
    let mut result = number;
    for i in 2..((number as f64).sqrt() as u64)+1 {
        if number % i == 0 {
            result = i;
            break;
        }
    }

    if result == number {
        return vec![number];
    } else {
        let mut v1 = vec![result];
        let mut v2 = prime_factorization(number / result);

        v1.append(&mut v2);

        return v1;
    }
}

fn calc_distance(xa: f64, ya: f64, xb: f64, yb: f64)->f64 {
    (f64::powf(xb-xa, 2.0) + f64::powf(yb-ya, 2.0)).sqrt()
}

fn calc_triangle_area(x1: f64, y1: f64, x2: f64, y2: f64, x3: f64, y3: f64) -> f64 {
    1.0/2.0 * ((x1-x3)*(y2-y3)-(x2-x3)*(y1-y3)).abs()
}

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

// 最大公約数
fn gcd(a: i64, b: i64) -> i64 {
    match b {
        0 => a,
        _ => gcd(b, a % b)
    }
}

// 最小公倍数
fn lcm(a: i64, b: i64) -> i64 {
    let g = gcd(a ,b);
    a / g * b
}

// 階乗-dp (overflow回避で1000000007の余りを使って計算)
// 普通の階乗はmに1を指定
fn kaijou_dp(n: i64) -> i64 {
    let mut dp: Vec<i64> = vec![0; n as usize+1];
    dp[0] = 1;
    dp[1] = 1;

    for i in 1..n {
        dp[i as usize+1] = dp[i as usize] % MOD * (i+1)  % MOD;
    }
    return dp[n as usize];
}

// 階乗
fn kaijou(n: i64)->i64 {
    if n == 1 {
        return n;
    }
    return n * kaijou(n-1);
}

// 順列全列挙
pub trait LexicalPermutation {
    /// Return `true` if the slice was permuted, `false` if it is already
    /// at the last ordered permutation.
    fn next_permutation(&mut self) -> bool;
}

impl<T> LexicalPermutation for [T] where T: Ord {
    /// Original author in Rust: Thomas Backman <serenity@exscape.org>
    /// let mut data = [1, 2, 3];
    //    let mut permutations = Vec::new();
    //
    //    loop {
    //        permutations.push(data.to_vec());
    //        if !data.next_permutation() {
    //            break;
    //        }
    //    }
    //
    //    println!("{:?}", permutations);
    //    // [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
    fn next_permutation(&mut self) -> bool {
        // These cases only have 1 permutation each, so we can't do anything.
        if self.len() < 2 { return false; }

        // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
        let mut i = self.len() - 1;
        while i > 0 && self[i-1] >= self[i] {
            i -= 1;
        }

        // If that is the entire vector, this is the last-ordered permutation.
        if i == 0 {
            return false;
        }

        // Step 2: Find the rightmost element larger than the pivot (i-1)
        let mut j = self.len() - 1;
        while j >= i && self[j] <= self[i-1]  {
            j -= 1;
        }

        // Step 3: Swap that element with the pivot
        self.swap(j, i-1);

        // Step 4: Reverse the (previously) weakly decreasing part
        self[i..].reverse();

        true
    }
}

//iより小さい数字の数 = lower_bound(&a, i) as i64;
//iより大きい数字の数 = n - upper_bound(&c, i) as i64;
fn lower_bound<T: Ord>(vec: &Vec<T>, x: T) -> usize {
    let (mut left, mut right): (i64, i64) = (-1, vec.len() as i64);

    while (right - left) > 1 {
        let mid = (right + left) / 2;

        if x <= vec[mid as usize] {
            right = mid;
        } else {
            left = mid;
        }
    }

    return right as usize;
}

fn upper_bound<T: Ord>(vec: &Vec<T>, x: T) -> usize {
    let (mut left, mut right): (i64, i64) = (-1, vec.len() as i64);

    while (right - left) > 1 {
        let mid = (right + left) / 2;

        if x < vec[mid as usize] {
            right = mid;
        } else {
            left = mid;
        }
    }

    return right as usize;
}