CF 220C Little Elephant and Shifts

题目链接:http://codeforces.com/problemset/problem/220/C


题目大意:

a为长度为n的不变的串,b为长度为n的可循环左移的串.

a,b均由1~n组成,每个数在每串中用一次.

a串与b串的值为min{ |i-j| },ai==bj

求所有bi,bi+1...bn,bn-1...b1,与a串的值.


题目思路:

1<=n<=100000,朴素算法O(n^2)肯定不行,所以想到了O(nlogn)的线段树,纠结了很久,搞出个维护绝对值的最小值,但是表示没有任何想法= =...

之后发现对于每次操作,要么是某些数+1,要么是某些数-1(首个数除外)...本来还想用线段树来写,写着写着发现怎么看怎么像优先队列+延迟标记...


代码:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

#define ll long long
#define ls rt<<1
#define rs ls|1
#define lson l,mid,ls
#define rson mid+1,r,rs
#define middle (l+r)>>1
#define eps (1e-9)
#define type int
#define clr_all(x,c) memset(x,c,sizeof(x))
#define clr(x,c,n) memset(x,c,sizeof(x[0])*(n+1))
#define MOD 1000000007
#define inf 0x3f3f3f3f
#define pi acos(-1.0)

template <class T> void _swap(T &x,T &y){T t=x;x=y;y=t;}
template <class T> T _max(T x,T y){return x>y? x:y;}
template <class T> T _min(T x,T y){return x<y? x:y;}
int test,cas;
const int M=100000 +5;

int n,m;
int ap[M],b[M],cur[M];

struct node{
	int id,cur,num;
	node(){}
	node(int _i,int _c,int _n){id=_i,cur=_c,num=_n;}
	bool operator < (const node& t) const{
		return num > t.num;
	}
};
priority_queue<node>rgt,lft;
int covr,covl;

void run(){
	int i,j;
	for(i=1;i<=n;i++){
		scanf("%d",&j);
		ap[j]=i;
	}
	while(!rgt.empty()) rgt.pop();
	while(!lft.empty()) lft.pop();
	clr(cur,0,n+1);
	for(i=1;i<=n;i++){
		scanf("%d",&b[i]);
		if(i>ap[b[i]]) rgt.push(node(b[i],0,i-ap[b[i]]));
		else lft.push(node(b[i],0,ap[b[i]]-i));
	}
	covr=covl=0;
	node r,l;
	for(i=1;;i++){
		while(!rgt.empty()){
			r=rgt.top();
			if(r.cur!=cur[r.id]) rgt.pop();
			else if(r.num+covr==0){
				rgt.pop();
				lft.push(node(r.id,r.cur,-covl));
			}else break;
		}
		while(!lft.empty()){
			l=lft.top();
			if(l.cur!=cur[l.id]) lft.pop();
			else break;
		}
		int ans=inf;
		if(!rgt.empty()) ans=_min(ans,rgt.top().num+covr);
		if(!lft.empty()) ans=_min(ans,lft.top().num+covl);
		printf("%d\n",ans);
		if(i==n) break;
		covr--,covl++;
		cur[b[i]]++;
		if(n>ap[b[i]]) rgt.push(node(b[i],cur[b[i]],n-ap[b[i]]-covr));
		else lft.push(node(b[i],cur[b[i]],-covl));
	}
}

void preSof(){
}

int main(){
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	preSof();
	//run();
	while(~scanf("%d",&n)) run();
	//for(scanf("%d",&test),cas=1;cas<=test;cas++) run();
	return 0;
}


你可能感兴趣的:(CF 220C Little Elephant and Shifts)