跳到正文

个人记录

周二下午练习课总结(第一题)

fuhuangyi约 4 分钟
原文
文章信息与版本

文章信息

发布
2026年9月9日
收录
2026年9月9日
更新
2026年11月11日
篇幅
约 4 分钟

版本

  1. v1当前

T1 T816071 [ABC237D] LR insertion

错误代码❌

这道题我在考试的时候用的是暴力解,得了60分(TLETLE了八个点):

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,cnt;
char x;
deque<int> q;
signed main()
{
	q.push_back(0);
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>x;
		cnt++;
		if(x=='L')
		{
			int c;
			for(int j=1;j<=q.size();j++)
			{
				q.push_back(q.front());
				q.pop_front();
				if(q.back()==i-1)
				{
					c=j;
				}
			}
			for(int j=1;j<=c-1;j++)
			{
				q.push_back(q.front());
				q.pop_front();
			}
			q.push_back(cnt);
			for(int j=c;j<=q.size()-1;j++)
			{
				q.push_back(q.front());
				q.pop_front();
			}
		}
		else
		{
			int c;
			for(int j=1;j<=q.size();j++)
			{
				q.push_back(q.front());
				q.pop_front();
				if(q.back()==i-1)
				{
					c=j;
				}
			}
			for(int j=1;j<=c;j++)
			{
				q.push_back(q.front());
				q.pop_front();
			}
			q.push_back(cnt);
			for(int j=c+1;j<=q.size()-1;j++)
			{
				q.push_back(q.front());
				q.pop_front();
			}
		}
	}
	while(q.size())
	{
		cout<<q.front()<<" ";
		q.pop_front();
	}
	return 0;
}//其实可以改用数组的,这个太复杂了。

题目意思📚

题目意思很简单:

C++
当 s i为 L 时,在 A 中 i−1 的左侧插入 i;
当 s i为 R 时,在 A 中 i−1 的右侧插入 i。

就这两句,输入也很简单:

C++
N//字符串的个数
S//字符串

知识点🎫

就是双端队列

解题思路🧠

这题的思路不难想到,只要倒过来想就行了:

C++
当 s i为 L 时,在 A 中 i−1 的左侧插入 i;
当 s i为 R 时,在 A 中 i−1 的右侧插入 i。
       ||         ||
       \/         \/
当 s i为 L 时,在 A 中 i 的右侧插入 i−1 ;
当 s i为 R 时,在 A 中 i 的左侧插入 i−1 。

再把循环倒过来就好写了。

正确代码✅

代码真的很短:

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,cnt;
string x;
deque<int> q;//双端队列
signed main()
{
	cin>>n;
	q.push_back(n);//先把n放进去
	cin>>x;
	for(int i=n-1;i>=0;i--)
	{
		if(x[i]=='L')q.push_back(i);//如果是L就放右边
		else q.push_front(i);//如果是R就放左边
	}
	while(q.size())//输出队列
	{
		cout<<q.front()<<" ";
		q.pop_front();
	}
	return 0;
}
原文