B. Teams Formation
time limit per test 2 seconds
memory limit per test 256 megabytes
input standard input
output standard output
This time the Berland Team Olympiad in Informatics is held in a remote city that can only be reached by one small bus. Bus has npassenger seats, seat i can be occupied only by a participant from the city ai.
Today the bus has completed m trips, each time bringing n participants. The participants were then aligned in one line in the order they arrived, with people from the same bus standing in the order of their seats (i. e. if we write down the cities where the participants came from, we get the sequence a1, a2, ..., an repeated m times).
After that some teams were formed, each consisting of k participants form the same city standing next to each other in the line. Once formed, teams left the line. The teams were formed until there were no k neighboring participants from the same city.
Help the organizers determine how many participants have left in the line after that process ended. We can prove that answer doesn't depend on the order in which teams were selected.
Input
The first line contains three integers n, k and m (1 ≤ n ≤ 105, 2 ≤ k ≤ 109, 1 ≤ m ≤ 109).
The second line contains n integers a1, a2, ..., an (1 ≤ ai ≤ 105), where ai is the number of city, person from which must take seat i in the bus.
Output
Output the number of remaining participants in the line.
Examples
input
4 2 5
1 2 3 1
output
12
input
1 9 10
1
output
1
input
3 2 10
1 2 1
output
0
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
using namespace std;
int n,k,m;
int a[100005];
struct node
{
int v,num;
}itm[100005];
int cnt;
int main()
{
while(~scanf("%d%d%d",&n,&k,&m))
{
long long ans=0;
for(int i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
cnt=0;
for(int i=0;i<n;i++)
{
if(cnt==0 || itm[cnt-1].v!=a[i])
{
itm[cnt].v=a[i];
itm[cnt].num=1;
cnt++;
}
else
{
itm[cnt-1].num++;
int tp=itm[cnt-1].num%k;
ans+=(1ll)*(itm[cnt-1].num-tp)*m;
itm[cnt-1].num%=k;
if(itm[cnt-1].num==0)
{
cnt--;
}
}
}
int l=0,r=cnt-1;
while(l<r)
{
if(itm[l].v==itm[r].v)
{
long long tl=itm[l].num+itm[r].num;
ans+=1ll*(tl-tl%k)*(m-1);
if(tl%k==0)
{
l++,r--;
}
else
break;
}
else
break;
}
if(l==r)
{
long long tl=1ll*itm[l].num*m;
ans+=(tl-tl%k);
if(tl%k==0)
l++,r--;
}
while(r>=0 && l<cnt && l>r)
{
if(itm[l].v==itm[r].v)
{
long long tl=itm[l].num+itm[r].num;
ans+=1ll*(tl-tl%k);
if(tl%k==0)
l++,r--;
else
break;
}
else
break;
}
printf("%lld\n",1ll*n*m-ans);
}
}