#include<set>
#include<map>
#include<queue>
#include<vector>
#include<algorithm>
#include<bits/stdc++.h>
#define pr pair
#define f first
#define s second
#define ll long long
#define mp make_pair
#define pll pr<ll,ll>
#define pii pr<int,int>
#define piii pr<int,pii>
using namespace std;
int t[120][5];
int ad[120][120];
int a[200005][5];
int w[200005];
int lp[200005][120];
int d[5];
int us[120],q;
bool ud[5];
bool ap[120];
int lt[120],z;
int calc(int a[])
{
int rt=24*a[0]+6*a[1]+2*a[2]+a[3];
for(int i=0;i<1;i++) if(a[i]<a[1]) rt-=6;
for(int i=0;i<2;i++) if(a[i]<a[2]) rt-=2;
for(int i=0;i<3;i++) if(a[i]<a[3]) rt-=1;
return rt;
}
int main()
{
ios_base::sync_with_stdio(0);
for(int i=0;i<120;i++)
{
t[i][0]=i/24;
t[i][1]=i%24/6;
t[i][2]=i%6/2;
t[i][3]=i%2;
for(int j=0;j<5;j++) ud[j]=0;
for(int j=0;j<5;j++)
{
int k=t[i][j];
for(t[i][j]=0;t[i][j]<5;t[i][j]++)
{
if(!ud[t[i][j]])
{
k--;
if(k==-1)
{
ud[t[i][j]]=1;
break;
}
}
}
}
}
for(int i=0;i<120;i++)
{
for(int j=0;j<120;j++)
{
for(int k=0;k<5;k++)
{
d[k]=t[i][t[j][k]];
}
ad[i][j]=calc(d);
}
}
int n,k;
cin>>n>>k;
for(int i=0;i<n;i++) for(int j=0;j<k;j++) cin>>a[i][j],a[i][j]--;
for(int i=0;i<n;i++) for(int j=k;j<5;j++) a[i][j]=j;
for(int i=0;i<n;i++) w[i]=calc(a[i]);
for(int i=0;i<120;i++) lp[n][i]=n+1;
for(int i=n-1;i>=0;i--)
{
for(int j=0;j<120;j++) lp[i][j]=lp[i+1][j];
lp[i][w[i]]=i;
}
ll ans=0;
ap[0]=1;
int lc,nc,fr;
for(int i=0;i<n;i++)
{
z=1;
for(int j=1;j<120;j++) ap[j]=0;
nc=i;
q=0;
while(nc<n)
{
lc=nc;
nc=n;
fr=0;
for(int j=0;j<120;j++)
{
if(ap[j]) continue;
if(lp[i][j]<=nc)
{
nc=lp[i][j];
fr=j;
}
}
ans+=(nc-lc)*z;
us[q++]=fr;
for(int j=0;j<z;j++)
{
for(int k=0;k<q;k++)
{
int g=ad[lt[j]][us[k]];
if(ap[g]) continue;
lt[z++]=g;
ap[g]=1;
}
}
}
}
cout<<ans<<endl;
return 0;
}
1302. Deepest Leaves Sum | 1209. Remove All Adjacent Duplicates in String II |
994. Rotting Oranges | 983. Minimum Cost For Tickets |
973. K Closest Points to Origin | 969. Pancake Sorting |
967. Numbers With Same Consecutive Differences | 957. Prison Cells After N Days |
946. Validate Stack Sequences | 921. Minimum Add to Make Parentheses Valid |
881. Boats to Save People | 497. Random Point in Non-overlapping Rectangles |
528. Random Pick with Weight | 470. Implement Rand10() Using Rand7() |
866. Prime Palindrome | 1516A - Tit for Tat |
622. Design Circular Queue | 814. Binary Tree Pruning |
791. Custom Sort String | 787. Cheapest Flights Within K Stops |
779. K-th Symbol in Grammar | 701. Insert into a Binary Search Tree |
429. N-ary Tree Level Order Traversal | 739. Daily Temperatures |
647. Palindromic Substrings | 583. Delete Operation for Two Strings |
518. Coin Change 2 | 516. Longest Palindromic Subsequence |
468. Validate IP Address | 450. Delete Node in a BST |