Problem:
問題 G : Perm Query

問題文

\{1,  2,  … ,  N\}の順列 (p(1),  p(2),  … ,  p(n)) が与えられる．
(l_i,  r_i) からなるクエリが Q 個与えられるので，各クエリに対して以下の擬似コードによる処理結果を出力せよ．

ret   :=   0, (x(1),  x(2),  … ,  x(N))  :=  (1,  2,  … ,  N) とおく．

各i   ∈ \{1,   2,  … ,   N\} について y(i) := p(x(i)) とする．

各i   ∈ \{1,   2,  … ,   N\} について x(i)   =  y(i)とする．

ret   :=  ret + x(l_i) + x(l_i+1) + …  + x(r_i)

もし (x(l_i),  x(l_i+1),  … ,  x(r_i)) = (l_i,  l_i+1,  … ,  r_i) なら (ret   mod10^9+7) を出力して終了する．そうでないなら 2 行目に戻る．

入力形式

入力は以下の形式で与えられる

N Q
p(1) p(2) ... p(N)
l_0 r_0
...
l_{Q-1} r_{Q-1}

出力形式

各クエリに対する出力を1行ずつ出力せよ．

制約

1 ≤ N ≤ 10^5

1 ≤ Q ≤ 10^4

(p_1,  p_2,  … ,  p_N) は (1,  2,  … ,  N) の順列になっている．

各 i に対して，ある 1 ≤ k ≤ 40 が存在して，p^k(i)=i となる．ここで，p^k(i) は p(p(p(… p(i)… ))) で p が k 回現れるもの．

1 ≤ l_i   ≤   r_i   ≤ N

入出力例

入力例 1

5 2
5 1 2 3 4
1 1
2 4

出力例 1

15
45

擬似コード中の順列(x(1),   x(2),   … ,  x(N))は以下のように変化する．

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

入力例 2

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

出力例 2

660
90
6
178
67

Solution in Rust (judge verdict: Accepted)

extern crate core;

use std::fmt;
use std::i32::{MAX};
use std::cmp::{Ordering, min, max };
use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut, SubAssign, Range};
use std::collections::{BTreeMap, VecDeque, BinaryHeap, BTreeSet, HashMap};
use std::fmt::{Display, Formatter, Error};

fn show<T: Display>(vec: &Vec<T>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        print!("[{}", vec[0]);
        for i in 1 .. vec.len() {
            print!(", {}", vec[i]);
        }
        println!("]");
    }
}
fn show2<T: Display>(vec: &Vec<Vec<T>>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        for l in vec {
            show(l);
        }
    }
}
macro_rules! read_lines{
    ($count: expr; $delimiter: expr; $ty: ty) => {{
        let line_count = $count;
        let mut vec: Vec<Vec<$ty>> = Vec::with_capacity(line_count);
        for _ in 0 .. line_count {
            vec.push(read_line!($delimiter; $ty));
        }
        vec
    }};
    ($count: expr; $ty: ty) => {{
        let line_count = $count;
        let mut vec: Vec<$ty> = Vec::with_capacity(line_count);
        for _ in 0 .. line_count {
            vec.push(read_value!());
        }
        vec
    }}
}
macro_rules! read_line{
    () => {{
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        line
    }};
    (delimiter: ' ') => {
        read_line!().split_whitespace().map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (delimiter: $p:expr) => {
        read_line!().split($p).map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (' ') => {
        read_line!(delimiter: ' ')
    };
    ($delimiter:expr) => {
        read_line!(delimiter: $delimiter)
    };
    (' '; $ty:ty) => {
        read_line!().split_whitespace().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
    ($delimiter:expr; $ty:ty) => {
        read_line!($delimiter).into_iter().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
}
macro_rules! read_value{
    () => {
        read_line!().trim().parse().ok().unwrap()
    }
}
macro_rules! let_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}

macro_rules! let_mut_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let mut $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}
#[derive(Clone)]
struct Bit {
    vec: Vec<i64>
}
const MOD: i64 = 1000000007i64;
impl Bit {
    fn new(size: usize) -> Bit {
        Bit{vec: vec![0i64; size]}
    }
    fn add(&mut self, mut pos: usize, value: i64) {
        while pos < self.vec.len() {
            self.vec[pos] += value;
            self.vec[pos] %= MOD;
            pos += !pos & (pos + 1);
        }
    }
    fn get(&self, mut pos: usize) -> i64 {
        let mut result = 0i64;
        let mut pos = pos as i32;
        while pos >= 0 {
            result += self.vec[pos as usize];
            result %= MOD;
            pos -= !pos & (pos + 1);
        }
        result
    }
}
struct LcmSegmentTree {
    vec: Vec<Vec<i64>>
}
fn gcd(a: i64, b: i64) -> i64 {
    match b {
        0 => a,
        _ => gcd(b, a % b),
    }
}
fn lcm(a: i64, b: i64) -> i64 {
    a / gcd(a, b) * b
}
impl LcmSegmentTree {
    fn new(initial : Vec<i64>) -> LcmSegmentTree {
        let mut len = initial.len();
        let mut vec = vec![initial];
        while len > 1 {
            vec.push(vec![1i64; len / 2]);
            len /= 2;
        }
        for i in 1 .. vec.len() {
            for j in 0 .. vec[i - 1].len() {
                if j / 2 < vec[i].len() {
                    vec[i][j / 2] = lcm(vec[i][j / 2], vec[i - 1][j]);
                }
            }
        }
        LcmSegmentTree{vec: vec}
    }
    fn lcm(&self, mut from: usize, mut to: usize) -> i64 {
        let mut result = 1i64;
        let mut from = from as i32;
        let mut to = to as i32;
        for v in &self.vec {
            if from % 2 == 1 {
                result = lcm(result, v[from as usize]);
                from += 1;
            }
            if to % 2 == 0 {
                result = lcm(result, v[to as usize]);
                to -= 1;
            }
            if to < from {
                break;
            }
            from /= 2;
            to /= 2;
        }
        result
    }
}
fn main(){
    const MAX_LOOP: usize = 40;
    let_all!(n: usize, q: usize);
    let permutations: Vec<usize> = read_line!(' '; usize).iter().map(|x| x - 1).collect();
    let mut loop_length = vec![MAX_LOOP + 1; n];
    let mut loop_sum = vec![0i64; n];
    let mut bits = vec![Bit::new(n); MAX_LOOP + 1];
    for i in 0 .. n {
        if loop_length[i] == MAX_LOOP + 1 {
            let mut length = 1;
            let mut sum = (i + 1) as i64;
            let mut current = permutations[i];
            while current != i {
                length += 1;
                sum += (current + 1) as i64;
                sum %= MOD;
                current = permutations[current];
            }
            loop_length[i] = length;
            loop_sum[i] = sum;
            current = permutations[i];
            while current != i {
                loop_length[current] = length;
                loop_sum[current] = sum;
                current = permutations[current];
            }
        }
        bits[loop_length[i]].add(i, loop_sum[i]);
    }
    let bits = bits;
    let lcm_tree = LcmSegmentTree::new(loop_length.iter().map(|&x| x as i64).collect());
    for _ in 0 .. q {
        let_all!(l: usize, r: usize);
        let l = l - 1;
        let r = r - 1;
        let loop_length = lcm_tree.lcm(l, r);
        let mut result = 0i64;
        for i in 1 .. MAX_LOOP + 1 {
            result += bits[i].get(r) * ((loop_length / i as i64) % MOD) % MOD;
            if l > 0 {
                result -= bits[i].get((l - 1) as usize) * ((loop_length / i as i64) % MOD) % MOD;
            }
            result = (result % MOD + MOD) % MOD;
        }
        println!("{}", result);
    }
}