Problem:
Score : 600 points

Problem Statement

We have N colored balls arranged in a row from left to right; the color of the i-th ball from the left is c_i.

You are given Q queries. The i-th query is as follows: how many different colors do the l_i-th through r_i-th balls from the left have?

Constraints

1\leq N,Q \leq 5 \times 10^5

1\leq c_i \leq N

1\leq l_i \leq r_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N Q
c_1 c_2 \cdots c_N
l_1 r_1
l_2 r_2
:
l_Q r_Q

Output

Print Q lines. The i-th line should contain the response to the i-th query.

Sample Input 1

4 3
1 2 1 3
1 3
2 4
3 3

Sample Output 1

2
3
1

The 1-st, 2-nd, and 3-rd balls from the left have the colors 1, 2, and 1 - two different colors.

The 2-st, 3-rd, and 4-th balls from the left have the colors 2, 1, and 3 - three different colors.

The 3-rd ball from the left has the color 1 - just one color.

Sample Input 2

10 10
2 5 6 5 2 1 7 9 7 2
5 5
2 4
6 7
2 2
7 8
7 9
1 8
6 9
8 10
6 8

Sample Output 2

1
2
2
1
2
2
6
3
3
3

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

#![allow(unused_imports, non_snake_case)]
#![allow(dead_code)]
use crate::{arraylist::List, data_structure::segment_tree::segtree::SegTree, scanner::Scanner};
fn main() {
    let mut scan = Scanner::new();
    let n = scan.read::<i32>();
    let q = scan.read::<i32>();
    let c = List::acc(n, |_| scan.read::<i32>() - 1);
    let mut lr = List::acc(q, |i| (i, scan.read::<i32>() - 1..=scan.read::<i32>() - 1));
    lr.sort_by_key(|r| *r.1.end());
    let mut most_left = list ! ( - 1 ; n );
    let mut x = 0;
    let mut seg = SegTree::new(list ! ( 0 ; n ), 0, |a, b| a + b);
    let mut ret = list ! ( 0 ; q );
    for &(i, ref r) in &lr {
        while x <= *r.end() {
            if most_left[c[x]] != -1 {
                seg.set(most_left[c[x]], 0);
            }
            most_left[c[x]] = x;
            seg.set(x, 1);
            x += 1;
        }
        ret[i] = seg.get(r.clone());
    }
    println!("{}", ret.join("\n"));
}
pub mod data_structure {
    pub mod segment_tree {
        pub mod segtree {
            use crate::arraylist::List;
            use crate::ext::range::IntRangeBounds;
            use std::ops::{Range, RangeBounds};
            pub struct SegTree<'a> {
                node: List<i64>,
                op: Box<dyn Fn(i64, i64) -> i64 + 'a>,
                zero: i64,
                n: i32,
            }
            impl<'a> SegTree<'a> {
                pub fn new<B>(v: List<i64>, zero: i64, op: B) -> SegTree<'a>
                where
                    B: Fn(i64, i64) -> i64 + 'a,
                {
                    let size = v.ilen();
                    let mut n = 1i32;
                    while n < size {
                        n *= 2
                    }
                    let mut node = List::init(zero, 2 * n - 1);
                    for i in 0..size {
                        node[i + n - 1] = v[i]
                    }
                    for i in (0..n - 1).rev() {
                        node[i] = op(node[2 * i + 1], node[2 * i + 2])
                    }
                    SegTree {
                        node,
                        op: Box::new(op),
                        zero,
                        n,
                    }
                }
                pub fn set(&mut self, mut x: i32, value: i64) {
                    x += self.n - 1;
                    self.node[x] = value;
                    while x > 0 {
                        x = (x - 1) / 2;
                        self.node[x] = (self.op)(self.node[2 * x + 1], self.node[2 * x + 2]);
                    }
                }
                pub fn get1(&self, i: i32) -> i64 {
                    self.getrec(i..i + 1, 0, 0..self.n)
                }
                pub fn get<T>(&self, query: T) -> i64
                where
                    T: RangeBounds<i32>,
                {
                    self.getrec(query.to_harfopen(0, self.n), 0, 0..self.n)
                }
                fn getrec(&self, query: Range<i32>, k: i32, range: Range<i32>) -> i64 {
                    if query.separate_range(&range) {
                        return self.zero;
                    }
                    if query.contain_range(&range) {
                        return self.node[k];
                    }
                    let vl = self.getrec(
                        query.clone(),
                        2 * k + 1,
                        range.start..(range.start + range.end) / 2,
                    );
                    let vr = self.getrec(
                        query.clone(),
                        2 * k + 2,
                        (range.start + range.end) / 2..range.end,
                    );
                    (self.op)(vl, vr)
                }
            }
        }
    }
}
pub mod scanner {
    use crate::arraylist::List;
    use std::io::{stdin, BufReader, Bytes, Read, Stdin};
    use std::str::FromStr;
    macro_rules ! impl_readxn { ( $ name : ident , $ ( $ tpe : ident ) ,+ ) => { pub fn $ name <$ ( $ tpe : FromStr ) ,+> ( & mut self , n : i32 ) -> List < ( $ ( $ tpe ) ,+ ) > { ( 0 .. n ) . map ( | _ | ( $ ( self . read ::<$ tpe > ( ) ) ,+ ) ) . collect ( ) } } ; }
    pub struct Scanner {
        buf: Bytes<BufReader<Stdin>>,
    }
    impl Scanner {
        pub fn new() -> Scanner {
            Scanner {
                buf: BufReader::new(stdin()).bytes(),
            }
        }
        pub fn read_next<T: FromStr>(&mut self) -> Option<T> {
            let token = self
                .buf
                .by_ref()
                .map(|c| c.unwrap() as char)
                .skip_while(|c| c.is_whitespace())
                .take_while(|c| !c.is_whitespace())
                .collect::<String>();
            token.parse::<T>().ok()
        }
        pub fn read<T: FromStr>(&mut self) -> T {
            self.read_next().unwrap()
        }
        pub fn readn<T: FromStr>(&mut self, n: i32) -> List<T> {
            (0..n).map(|_| self.read::<T>()).collect()
        }
        pub fn chars(&mut self) -> List<char> {
            self.read::<String>().chars().collect()
        }
        impl_readxn!(read2n, P, Q);
        impl_readxn!(read3n, P, Q, R);
        impl_readxn!(read4n, P, Q, R, S);
        impl_readxn!(read5n, P, Q, R, S, T);
    }
}
pub mod arraylist {
    use crate::{ext::range::IntRangeBounds, independent::integer::Int};
    use std::fmt::Formatter;
    use std::iter::FromIterator;
    use std::ops::{Index, IndexMut, RangeBounds};
    use std::slice::Iter;
    #[derive(Clone, PartialEq, Eq)]
    pub struct List<T> {
        pub vec: Vec<T>,
    }
    impl<T> List<T> {
        #[inline]
        pub fn new() -> List<T> {
            List { vec: vec![] }
        }
        #[inline]
        pub fn init(init: T, n: i32) -> List<T>
        where
            T: Clone,
        {
            List {
                vec: vec![init; n as usize],
            }
        }
        #[inline]
        pub fn from_vec(vec: Vec<T>) -> List<T> {
            List { vec }
        }
        #[inline]
        pub fn acc<'a, S>(n: i32, mut f: S) -> List<T>
        where
            S: FnMut(i32) -> T + 'a,
        {
            (0..n).map(|i| f(i)).collect()
        }
        #[inline]
        pub fn ilen(&self) -> i32 {
            self.vec.len() as i32
        }
        #[inline]
        pub fn iter(&self) -> Iter<'_, T> {
            self.vec.iter()
        }
        #[inline]
        pub fn push(&mut self, item: T) {
            self.vec.push(item);
        }
        #[inline]
        pub fn sort(&mut self)
        where
            T: Ord,
        {
            self.vec.sort();
        }
        #[inline]
        pub fn reverse(&mut self) {
            self.vec.reverse();
        }
        #[inline]
        pub fn sort_by<F>(&mut self, compare: F)
        where
            F: FnMut(&T, &T) -> std::cmp::Ordering,
        {
            self.vec.sort_by(compare)
        }
        #[inline]
        pub fn sort_by_key<K, F>(&mut self, compare: F)
        where
            F: FnMut(&T) -> K,
            K: Ord,
        {
            self.vec.sort_by_key(compare)
        }
        #[inline]
        pub fn first(&self) -> Option<&T> {
            self.vec.first()
        }
        #[inline]
        pub fn last(&self) -> Option<&T> {
            self.vec.last()
        }
        #[inline]
        pub fn pop(&mut self) -> Option<T> {
            self.vec.pop()
        }
        #[inline]
        pub fn swap(&mut self, i: i32, j: i32) {
            self.vec.swap(i as usize, j as usize);
        }
        #[inline]
        pub fn append(&mut self, mut other: Self) {
            self.vec.append(&mut other.vec);
        }
        #[inline]
        pub fn extend(&mut self, other: impl Iterator<Item = T>) {
            self.vec.extend(other);
        }
        #[inline]
        pub fn mrr(&self) -> std::iter::Cloned<Iter<T>>
        where
            T: Clone,
        {
            self.iter().cloned()
        }
        #[inline]
        pub fn join(&self, sep: &str) -> String
        where
            T: std::fmt::Display,
        {
            self.iter()
                .map(|x| format!("{}", x))
                .collect::<Vec<_>>()
                .join(sep)
        }
        #[inline]
        pub fn map<B, F>(&self, f: F) -> List<B>
        where
            T: Clone,
            F: FnMut(T) -> B,
        {
            self.mrr().map(f).collect()
        }
        #[inline]
        pub fn filter<P>(&self, predicate: P) -> List<T>
        where
            T: Clone,
            P: FnMut(&T) -> bool,
        {
            self.mrr().filter(predicate).collect()
        }
        #[inline]
        pub fn filter_map<B, F>(&self, f: F) -> List<B>
        where
            T: Clone,
            F: FnMut(T) -> Option<B>,
        {
            self.mrr().filter_map(f).collect()
        }
        #[doc = " |acc, x| -> acc"]
        #[inline]
        pub fn fold<B, F>(&self, init: B, f: F) -> B
        where
            T: Clone,
            F: FnMut(B, T) -> B,
        {
            self.mrr().fold(init, f)
        }
        #[inline]
        pub fn any<P>(&self, predicate: P) -> bool
        where
            P: FnMut(&T) -> bool,
        {
            self.iter().any(predicate)
        }
        #[inline]
        pub fn all<P>(&self, predicate: P) -> bool
        where
            P: FnMut(&T) -> bool,
        {
            self.iter().all(predicate)
        }
        #[inline]
        pub fn sum(&self) -> T
        where
            T: Int,
        {
            self.iter().cloned().fold(T::zero(), |acc, x| acc + x)
        }
        #[inline]
        pub fn enumerate(&self) -> List<(i32, T)>
        where
            T: Clone,
        {
            self.mrr().enumerate().map(|p| (p.0 as i32, p.1)).collect()
        }
        #[inline]
        pub fn find<P>(&self, mut predicate: P) -> Option<&T>
        where
            P: FnMut(&T) -> bool,
        {
            self.iter().find(|x| predicate(*x))
        }
        #[inline]
        pub fn index_of<P>(&self, mut predicate: P) -> Option<i32>
        where
            P: FnMut(&T) -> bool,
        {
            self.iter()
                .enumerate()
                .find(|&(_i, x)| predicate(x))
                .map(|p| p.0 as i32)
        }
        #[inline]
        pub fn to<B: FromIterator<T>>(&self) -> B
        where
            T: Clone,
        {
            self.mrr().collect()
        }
        #[inline]
        pub fn min(&self) -> Option<&T>
        where
            T: Ord,
        {
            self.iter().min()
        }
        #[inline]
        pub fn max(&self) -> Option<&T>
        where
            T: Ord,
        {
            self.iter().max()
        }
        #[inline]
        pub fn argmin(&self) -> Option<i32>
        where
            T: Ord,
        {
            let item = self.iter().min()?;
            self.iter()
                .enumerate()
                .find(|p| p.1 == item)
                .map(|p| p.0 as i32)
        }
        #[inline]
        pub fn argmax(&self) -> Option<i32>
        where
            T: Ord,
        {
            let item = self.iter().max()?;
            self.iter()
                .enumerate()
                .find(|p| p.1 == item)
                .map(|p| p.0 as i32)
        }
        #[inline]
        pub fn part<U>(&self, range: U) -> List<T>
        where
            T: Clone,
            U: RangeBounds<i32>,
        {
            List::from_vec(
                self.vec[range.lower_bound(0) as usize..range.upper_bound(self.ilen()) as usize]
                    .to_vec(),
            )
        }
        #[inline]
        pub fn first_exn(&self) -> &T {
            self.first().unwrap()
        }
        #[inline]
        pub fn last_exn(&self) -> &T {
            self.last().unwrap()
        }
        #[inline]
        pub fn pop_exn(&mut self) -> T {
            self.pop().unwrap()
        }
        #[inline]
        pub fn min_exn(&self) -> &T
        where
            T: Ord,
        {
            self.min().unwrap()
        }
        #[inline]
        pub fn max_exn(&self) -> &T
        where
            T: Ord,
        {
            self.max().unwrap()
        }
        #[inline]
        pub fn argmin_exn(&self) -> i32
        where
            T: Ord,
        {
            self.argmin().unwrap()
        }
        #[inline]
        pub fn argmax_exn(&self) -> i32
        where
            T: Ord,
        {
            self.argmax().unwrap()
        }
        #[inline]
        pub fn find_exn<P>(&self, predicate: P) -> &T
        where
            P: FnMut(&T) -> bool,
        {
            self.find(predicate).unwrap()
        }
        #[inline]
        pub fn index_of_exn<P>(&self, predicate: P) -> i32
        where
            P: FnMut(&T) -> bool,
        {
            self.index_of(predicate).unwrap()
        }
    }
    impl<T> std::ops::BitXorAssign<T> for List<T> {
        #[inline]
        fn bitxor_assign(&mut self, rhs: T) {
            self.push(rhs);
        }
    }
    impl<T> Index<i32> for List<T> {
        type Output = T;
        #[inline]
        fn index(&self, index: i32) -> &Self::Output {
            if cfg!(debug_assertions) {
                self.vec.index(index as usize)
            } else {
                unsafe { self.vec.get_unchecked(index as usize) }
            }
        }
    }
    impl<T> IndexMut<i32> for List<T> {
        #[inline]
        fn index_mut(&mut self, index: i32) -> &mut Self::Output {
            if cfg!(debug_assertions) {
                self.vec.index_mut(index as usize)
            } else {
                unsafe { self.vec.get_unchecked_mut(index as usize) }
            }
        }
    }
    impl<T> FromIterator<T> for List<T> {
        fn from_iter<U: IntoIterator<Item = T>>(iter: U) -> Self {
            List {
                vec: iter.into_iter().collect(),
            }
        }
    }
    impl<T> IntoIterator for List<T> {
        type Item = T;
        type IntoIter = std::vec::IntoIter<T>;
        fn into_iter(self) -> std::vec::IntoIter<T> {
            self.vec.into_iter()
        }
    }
    impl<'a, T> IntoIterator for &'a List<T> {
        type Item = &'a T;
        type IntoIter = Iter<'a, T>;
        fn into_iter(self) -> Iter<'a, T> {
            self.vec.iter()
        }
    }
    impl<T: std::fmt::Display> std::fmt::Display for List<T> {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(
                f,
                "{}",
                self.iter()
                    .map(|x| format!("{}", x))
                    .collect::<Vec<_>>()
                    .join(" ")
            )
        }
    }
    impl<T: std::fmt::Debug> std::fmt::Debug for List<T> {
        fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
            write!(
                f,
                "[{}]",
                self.iter()
                    .map(|x| format!("{:?}", x))
                    .collect::<Vec<_>>()
                    .join(", ")
            )
        }
    }
    impl<T> From<Vec<T>> for List<T> {
        fn from(vec: Vec<T>) -> Self {
            Self::from_vec(vec)
        }
    }
    impl<T: Clone> From<&[T]> for List<T> {
        fn from(slice: &[T]) -> Self {
            slice.iter().cloned().collect()
        }
    }
    #[macro_export]
    macro_rules ! list { ( ) => { $ crate :: arraylist :: List :: new ( ) } ; ( $ ( $ v : expr ) ,+ $ ( , ) ? ) => { $ crate :: arraylist :: List :: from_vec ( [ $ ( $ v ) ,+ ] . to_vec ( ) ) } ; ( $ v : expr ; $ a : expr ) => { $ crate :: arraylist :: List :: init ( $ v , $ a ) } ; ( $ v : expr ; $ a : expr ; $ ( $ rest : expr ) ;+ ) => { $ crate :: arraylist :: List :: init ( list ! ( $ v ; $ ( $ rest ) ;+ ) , $ a ) } ; }
}
pub mod ext {
    pub mod range {
        use crate::independent::integer::Int;
        use std::cmp::{max, min};
        use std::ops::{Bound, Range, RangeBounds};
        pub trait IntRangeBounds<U: Int>: RangeBounds<U> {
            fn lbopt(&self) -> Option<U> {
                match self.start_bound() {
                    Bound::Included(x) => Some(*x),
                    Bound::Excluded(x) => Some(*x + U::one()),
                    Bound::Unbounded => None,
                }
            }
            fn ubopt(&self) -> Option<U> {
                match self.end_bound() {
                    Bound::Included(x) => Some(*x + U::one()),
                    Bound::Excluded(x) => Some(*x),
                    Bound::Unbounded => None,
                }
            }
            #[doc = " inclusive"]
            fn lower_bound(&self, limit: U) -> U {
                self.lbopt().map_or(limit, |x| max(limit, x))
            }
            #[doc = " exclusive"]
            fn upper_bound(&self, limit: U) -> U {
                self.ubopt().map_or(limit, |x| min(limit, x))
            }
            fn to_harfopen(&self, lb: U, ub: U) -> Range<U> {
                self.lower_bound(lb)..self.upper_bound(ub)
            }
            fn within(&self, mut t: U) -> U {
                if let Some(x) = self.lbopt() {
                    if t < x {
                        t = x;
                    }
                }
                if let Some(x) = self.ubopt() {
                    if x <= t {
                        t = x - U::one();
                    }
                }
                t
            }
            fn width(&self) -> U {
                if self.empty() {
                    U::zero()
                } else {
                    self.ubopt().unwrap() - self.lbopt().unwrap()
                }
            }
            fn empty(&self) -> bool {
                self.lbopt().is_none()
                    || self.ubopt().is_none()
                    || !(self.lbopt().unwrap() < self.ubopt().unwrap())
            }
            fn contain_range(&self, inner: &Self) -> bool {
                (match (self.lbopt(), inner.lbopt()) {
                    (Some(a), Some(b)) => a <= b,
                    (None, _) => true,
                    (Some(_), None) => false,
                }) && (match (inner.ubopt(), self.ubopt()) {
                    (Some(a), Some(b)) => a <= b,
                    (_, None) => true,
                    (None, Some(_)) => false,
                })
            }
            fn separate_range(&self, other: &Self) -> bool {
                if let (Some(a), Some(b)) = (self.ubopt(), other.lbopt()) {
                    if a <= b {
                        return true;
                    }
                }
                if let (Some(a), Some(b)) = (other.ubopt(), self.lbopt()) {
                    if a <= b {
                        return true;
                    }
                }
                false
            }
            fn overlap(&self, other: &Self) -> Range<U> {
                let left = if let (Some(a), Some(b)) = (self.lbopt(), other.lbopt()) {
                    max(a, b)
                } else {
                    self.lbopt().or(other.lbopt()).unwrap()
                };
                let right = if let (Some(a), Some(b)) = (self.ubopt(), other.ubopt()) {
                    min(a, b)
                } else {
                    self.ubopt().or(other.ubopt()).unwrap()
                };
                left..right
            }
        }
        impl<T: ?Sized, U: Int> IntRangeBounds<U> for T where T: RangeBounds<U> {}
    }
}
pub mod independent {
    pub mod integer {
        pub trait Int:
            std::ops::Add<Output = Self>
            + std::ops::Sub<Output = Self>
            + std::ops::Mul<Output = Self>
            + std::ops::Div<Output = Self>
            + std::ops::Rem<Output = Self>
            + std::ops::AddAssign
            + std::ops::SubAssign
            + std::ops::MulAssign
            + std::ops::DivAssign
            + std::hash::Hash
            + PartialEq
            + Eq
            + PartialOrd
            + Ord
            + Copy
        {
            fn to_u8(&self) -> u8;
            fn to_u16(&self) -> u16;
            fn to_u32(&self) -> u32;
            fn to_u64(&self) -> u64;
            fn to_u128(&self) -> u128;
            fn to_i8(&self) -> i8;
            fn to_i16(&self) -> i16;
            fn to_i32(&self) -> i32;
            fn to_i64(&self) -> i64;
            fn to_i128(&self) -> i128;
            fn to_usize(&self) -> usize;
            fn to_isize(&self) -> isize;
            fn from_u8(x: u8) -> Self;
            fn from_u16(x: u16) -> Self;
            fn from_u32(x: u32) -> Self;
            fn from_u64(x: u64) -> Self;
            fn from_u128(x: u128) -> Self;
            fn from_i8(x: i8) -> Self;
            fn from_i16(x: i16) -> Self;
            fn from_i32(x: i32) -> Self;
            fn from_i64(x: i64) -> Self;
            fn from_i128(x: i128) -> Self;
            fn from_usize(x: usize) -> Self;
            fn from_isize(x: isize) -> Self;
            fn zero() -> Self;
            fn one() -> Self;
            fn next(&self) -> Self {
                *self + Self::one()
            }
        }
        macro_rules ! impl_integer_functions { ( $ selftpe : ident , $ ( $ tofn : ident , $ fromfn : ident , $ tpe : ident ) ,* ) => { $ ( fn $ tofn ( & self ) -> $ tpe { * self as $ tpe } fn $ fromfn ( x : $ tpe ) -> Self { x as $ selftpe } ) * } ; }
        macro_rules ! impl_integer { ( $ ( $ tpe : ident ) ,* ) => { $ ( impl Int for $ tpe { impl_integer_functions ! ( $ tpe , to_u8 , from_u8 , u8 , to_u16 , from_u16 , u16 , to_u32 , from_u32 , u32 , to_u64 , from_u64 , u64 , to_u128 , from_u128 , u128 , to_i8 , from_i8 , i8 , to_i16 , from_i16 , i16 , to_i32 , from_i32 , i32 , to_i64 , from_i64 , i64 , to_i128 , from_i128 , i128 , to_usize , from_usize , usize , to_isize , from_isize , isize ) ; fn zero ( ) -> Self { 0 } fn one ( ) -> Self { 1 } } ) * } ; }
        impl_integer!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, usize, isize);
    }
}