1540机器翻译

在这里插入图片描述

第一次:三组数据

第二次:AC

#include<iostream>
#include<queue>
using namespace std;
int main()
{
	queue<int>q;
	int M, N;
	cin >> M >> N;
	int cnt = 0,a;
	while (N--)
	{

		cin >> a;
		if (q.empty())
		{
			cnt++;
			q.push(a);
			//cout << a << " ";
		}
		else
		{
		int flag = 0;
		int i = 1;
		for (i; i <= q.size(); i++)
		{
		int head = q.front();
		if (head == a)
			{
			flag = 1; //break;
			q.pop();
			q.push(head);
			//很重要!!!!必须让循环完全进行,进行q.size次,把队逆转一次
			}
		else if (head != a)
			{
			q.pop();
			q.push(head);
			}
		}
		if (flag == 0 && q.size() < M)
		{
			q.push(a);
			cnt++;
			//cout << a << " ";
		}
		else if (flag == 0 && q.size() == M)//必须else if因为这是两个不同情况下的分支
		{
			q.pop();
			q.push(a);
			//cout << a << " ";
			cnt++;
		}

		}
	}
	cout << cnt;
	return 0;
}
/*4 20
1 2 1 2 1 2 3 3 3 3 4 1 3 1 3 4 5 6 1 2*/

自造数据:

4 20
1 2 1 2 1 2 3 3 3 3 4 1 3 1 3 4 5 6 1 2

错误所在:(1)

q.size() == M和q.size() < M必须列成两个对立分支if和else if

错误所在:(2)

当在队列中找到匹配的单词时,只需令flag=1做好标记;
p.pop();
p.push(head);
这些操作需要继续执行,完成队列翻转

猜你喜欢

转载自blog.csdn.net/helloworld0529/article/details/102981307