【题解】CF1279C Stack of Presents

Sol

考虑每次读进一个 \(b_i\),就从 \(a\) 数组中统计出答案。
每次对于一个 \(b_i\),可以将 \(a\) 数组中对应位置的前缀丢到一个 \(vis\) 里。
若后面读进的 \(b_i\)\(vis\) 值为 \(1\),那么他对于答案没有贡献。
因为题目中保证了各个数不唯一,所以这个做法一定是正确的。

Code

//LYC_music yyds!
#include<bits/stdc++.h>
#define IOS ios::sync_with_stdio(0)
#define lowbit(x) (x&(-x))
#define int long long
using namespace std;
int read()
{
	int pos=1,num=0;
	char ch=getchar();
	while (!isdigit(ch))
	{
		if (ch=='-') pos=-1;
		ch=getchar();
	}
	while (isdigit(ch))
	{
		num=num*10+(int)(ch-'0');
		ch=getchar();
	}
	return pos*num;
}
void write(int x)
{
	if (x<0)
	{
		putchar('-');
		write(-x);
		return;
	}
	if (x>=10) write(x/10);
	putchar(x%10+'0');
}
void writesp(int x)
{
	write(x);
	putchar(' ');
}
void writeln(int x)
{
	write(x);
	putchar('\n');
}
const int N=2e5+1;
int n,m,tot,ans,s[N],a[N],top,T,vis[N];
signed main()
{
	T=read();
	while (T--)
	{
		n=read(); m=read();	top=n;
		for (int i=1;i<=n;i++)
			s[top--]=read();
		tot=0; ans=0; top=n;
		memset(vis,0,sizeof(vis));
		for (int i=1;i<=m;i++)
		{
			int x=read();
			if (vis[x])
			{
				ans++; vis[x]=0; tot--;
			}
			else
			{
				do
				{
					vis[s[top]]=1;
					tot++;
				}while (s[top--]!=x);
				ans+=tot*2-1; tot--; 
			}
		}
		writeln(ans);
	}
}




posted @ 2021-08-31 17:22  dd_d  阅读(68)  评论(0)    收藏  举报