One day shooshuns found a sequence of n integers, written on a blackboard. The shooshuns can perform one operation with it, the operation consists of two steps:
- Find the number that goes k-th in the current sequence and add the same number to the end of the sequence;
- Delete the first number of the current sequence.
The shooshuns wonder after how many operations all numbers on the board will be the same and whether all numbers will ever be the same.
The first line contains two space-separated integers n and k (1 ≤ k ≤ n ≤ 105).
The second line contains n space-separated integers: a1, a2, ..., an (1 ≤ ai ≤ 105) — the sequence that the shooshuns found.
Print the minimum number of operations, required for all numbers on the blackboard to become the same. If it is impossible to achieve, print -1.
3 2 3 1 1
1
3 1 3 1 1
-1
In the first test case after the first operation the blackboard will have sequence [1, 1, 1]. So, one operation is enough to make all numbers the same. Thus, the answer equals one.
In the second test case the sequence will never consist of the same numbers. It will always contain at least two distinct numbers 3 and 1. Thus, the answer equals -1.
题目给出的操作是:把第k个数复制到最后,再删去第一个数。
这道题需要找规律:无论一共有多少个数,从第k个数往后的数就不可能删掉了,所以,如果从第k个数往后的数有不同的,则不可能完成。如果可以完成的话,再从第k个数往前看,如果遇到不一样的数,那么这个数直到第一个数都需要删除,操作次数就是这个数的下标。
代码如下:
#include <cstdio>
int main()
{
int n,k;
int num[100000+22];
bool flag;
while (~scanf ("%d %d",&n,&k))
{
for (int i = 1 ; i <= n ; i++)
scanf ("%d",&num[i]);
flag = true;
for (int i = k + 1 ; i <= n ; i++)
{
if (num[i] != num[k])
{
flag = false;
break;
}
}
if (!flag) //从k往后数字不一样,则不可能实现目标
{
printf ("-1\n");
continue;
}
int ans;
for (ans = k - 1 ; ans > 0 ; ans--) //从k-1个数往前看,有不同的数停止,前面的都需要删去
{
if (num[ans] != num[k])
break;
}
printf ("%d\n",ans);
}
return 0;
}