Delicious chocolate

Time:2021-3-19

Title Description

The supermarket is selling chocolates at a special price, and lucky is being greedy_ Dog saw it.
Chocolate from left to right in a row, a total of N, m kinds.
There is a strange rule in the supermarket, that is, when you buy chocolate, you must provide two numbers a and B, representing that you want to buy all the chocolates between the A and B chocolates (including a and b).
Suppose the unit price of all chocolates is 1 yuan. Lucky_ Dog wants to eat all kinds of chocolate, but he wants to save money. As lucky_ Dog’s friend, he asked you to help him decide how to choose a and B when buying chocolate.

Input format:
The first line contains two positive integers, N and m, which represent the total number and type of chocolate respectively.
The second line contains n integers, all between 1 and m, representing the type of chocolate.

Output format:
The output is only one line, containing two integers a and B, separated by a space, indicating the purchase range with the least cost and containing all kinds of chocolate.
If there are multiple qualified purchase intervals, output the one with the smallest a.

Thinking of solving problems

1. After selecting the head, add one to the counter for each new type
2. When the head type appears twice, the head moves one bit to the right
The idea of greedy algorithm: if the head type appears twice, it is definitely not the optimal solution, at least the right end of the head is better
3. Meet the conditions, update data a, B

Complete code

#include
int main()
{
	int n, m, i, a, b, cnt = 0, head = 0, d = 1000020;
	static int p[1000020], num[2020] = { 0 };
	scanf("%d%d", &n, &m);
	for (i = 0; i < n; i++) {
		scanf("%d", &p[i]);
		if (num[p[i]] == 0) {
			cnt++;
		}/*When a new type appears, add one to the counter*/
		num[p[i]]++;
		while (num[p[head]] > 1) {
			num[p[head]]--;
			head++;
		}/*The head type appears twice, and the head moves one bit to the right*/
		if (cnt == m) {
			if (i - head + 1 < d) {
				d = i - head + 1;
				a = head;
				b = a + d - 1;
			}
		}/*Meet the conditions, update data a, B*/
	}
	printf("%d %d", a + 1, b + 1);
	return 0;
}