//#include<bits/stdc++.h>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<stdlib.h>
#include<queue>
#include<map>
#include<vector>
#include<cmath>
#include<fstream>
#include <set>
//freopen(".in","r",stdin);
//freopen(".out","w",stdout);
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
const int  MAXN =5e5+10;
const int mod = 1e9 + 7;
const long long INF = 0x7f7f7f7f7f7f7f7f;
const int inf= 0x3f3f3f3f;
#define eps 1e-8
#define PI 3.1415926535898
#define lowbit(x) (x&(-x))
using namespace std ;
//getline(cin,s);
//set<ll>::iterator it;
//map<int,int>::iterator it;
typedef long long ll;
int n,q;
int c[MAXN],ans[MAXN],rt,pos[MAXN],sum,a[MAXN];
struct node{
	int l,r,index;
	/*bool operator <(const node& o)const
    {
        if(pos[l]==pos[o.l]) return r<o.r;
        return pos[l]<pos[o.l];
    }*/
}need[MAXN];
int cmp(node f,node s)
{
	if(pos[f.l]==pos[s.l])
	   return f.r<s.r;
	else return f.l<s.l;
}
void add(int x)
{
	a[c[x]]++;
	if(a[c[x]]==1) sum++;
}
void del(int x)
{
	a[c[x]]--;
	if(a[c[x]]==0) sum--;
}
int main()
{
	scanf("%d %d",&n,&q);
	rt=sqrt(1.0*n);
	for(int i=1;i<=n;i++)
	{
	    scanf("%d",&c[i]);
	    pos[i]=i/rt; 
	} 
	for(int i=1;i<=q;i++)
	{
		scanf("%d %d",&need[i].l,&need[i].r);
		need[i].index=i;
	}
	sort(need+1,need+1+q,cmp);
	int l=1,r=0;
	for(int i=1;i<=q;i++)
	{
		while(l<need[i].l)
		{
			del(l);
			l++;
		}
		while(l>need[i].l)
		{
			l--;
			add(l);
		}
		while(r<need[i].r)
		{
			r++;
			add(r);
		}
		while(r>need[i].r)
		{
			del(r);
			r--;
		}
		ans[need[i].index]=sum;
	}
	for(int i=1;i<=q;i++) printf("%d\n",ans[i]);
	return 0;
}

#include<iostream>
#include<vector>
using namespace std;

void compute(vector<vector<int> > & cost,vector<vector<int> > & best,
			 vector<int> & A,int s,int e){
	int minc = 0;
	int mink = -1;
	for(int k=s+1;k<=e;++k){
		if (cost[s][k-1] < 0){
			compute(cost,best,A,s,k-1);
		}
		if (cost[k][e] < 0) {
			compute(cost,best,A,k,e);
		}
		int c = cost[s][k-1] + A[s]*A[k]*A[e+1] + cost[k][e];
		if (mink < 0 || c < minc) {
			minc = c;
			mink = k;
		}
	}
	cost[s][e] = minc;
	best[s][e] = mink;
}

int main(){
	vector<vector<int> > cost,best;
	vector<int> A;
	int n;
	cin >> n;
	A.resize(n+1);
	for(int i=0;i<n;++i) {
		int r,c;
		cin >> r >> c;
		if (i==0){
			A[0] = r;
		}
		if (A[i] != r){ cout << "error";return (0);}
		A[i+1] = c;
	}
	cost.resize(n);
	best.resize(n);
	for(int i=0;i<n;++i){
		cost[i].resize(n);
		best[i].resize(n);
		for(unsigned j=0;j<cost[i].size();++j){
			cost[i][j] = -1;
			best[i][j] = -1;
		}
		cost[i][i]=0;
		best[i][i]=i;
	}
	compute(cost,best,A,0,n-1);
	cout << cost[0][n-1] << std::endl;
	return 0;
}