1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
#include <iostream>
#include <vector>

void display(int n, int k, int* arr)
{
	//std::cout << n;
	//std::cout << " ";
	//std::cout << k << std::endl;
	for (int i = 0; i < n; i++)
	{
		std::cout << arr[i];
		if (i < n - 1)
		{
			std::cout << " ";
		}
		else
		{
			std::cout << std::endl;
		}
	}
}

void swap(int* x, int* y)
{
	int temp = *x;
	*x = *y;
	*y = temp;
}

int countDistinct(int* arr, int n)
{
	int res = 1;

	for (int i = 1; i < n; i++)
	{
		int j = 0;
		for (j = 0; j < i; j++)
		{
			if (arr[i] == arr[j])
			{
				break;
			}
		}
		if (i == j)
		{
			res++;
		}
	}
	return res;
}

int moveFromTo(int* arr, int start, int end)
{
	for (int i = start; i < end; i++)
	{
		swap(&arr[i], &arr[i + 1]);
	}
	return end - start;
}


int sort(int* arr, int n, int k, std::vector<int> duplicated, std::vector<int> different)
{
	int steps = 0;
	for (int i = duplicated.size()-1; i >= 0; i--)
	{
		int start = duplicated.at(i);
		int end = different.at(duplicated.size() - i - 1);
		steps += moveFromTo(arr, start, end);
	}
	return steps;
	
}

std::vector<int> findDuplicated(int* arr, int k)
{
	std::vector<int> duplicates;
	for (int i = 1; i < k; i++)
	{
		int j = 0;
		for (j = 0; j < i; j++)
		{
			if (arr[i] == arr[j])
			{
				duplicates.push_back(i);
				break;
			}
		}
	}
	return duplicates;
}

std::vector<int> findDifferent(int* arr, int n, int k)
{
	std::vector<int> different;
	for (int i = k; i < n; i++)
	{
		bool various = true;
		for (int j = 0; j < k; j++)
		{
			if (arr[i] == arr[j])
			{
				various = false;
				break;
			}
		}
		if (various)
		{
			different.push_back(i);
		}
	}
	return different;
}

int main()
{
	// Number of bottles on the shelf
	int n;

	// Number of leftmost bottles
	int k;

	// Array of bottle brand
	int* brands;

	std::cin >> n >> k;

	brands = new int[n];

	for (int i = 0; i < n; i++)
	{
		std::cin >> brands[i];
	}


	int result;
	if (countDistinct(brands, n) < k)
	{
		result = -1;
	}
	else
	{
		std::vector<int> duplicated = findDuplicated(brands, k);
		std::vector<int> different = findDifferent(brands, n, k);
		
		result = sort(brands, n, k, duplicated, different);
	}
	std::cout << result;

	//display(n, k, brands);
	return 0;

}