1. 程式人生 > 實用技巧 >P1966 火柴排隊

P1966 火柴排隊

\(\text{Solution}\)

首先有一個結論:\(a\) 序列的第 \(k\) 大和 \(b\) 序列的第 \(k\) 大在相同的位置上兩列火柴的距離最小。

證明要用排序不等式,這裡不贅述。

關鍵是接下來如何處理。對於 \(a,b\) 陣列分別處理出 \(pos\) 陣列表示第 \(i\) 小的數在原陣列的下標為 \(pos[i]\)。這時我們想要 \(posa[i]\)\(posb[i]\) 相等。我們再搞個數組令 \(c[posa[i]]=posb[i]\),如果使這個陣列單調遞增就滿足了要求。

方便理解我們定義 \(A=\{4,1,2,3\},B=\{3,2,4,1\}\)

。則 \(posa=\{2,3,4,1\},posb=\{4,2,1,3\}\)。那麼 \(C=\{3,4,2,1\}\),我們嘗試理解 \(C\) 的第二項:\(A\) 陣列的第一小在 \(2\) 位置,\(B\) 陣列的第一小在 \(4\) 位置,那麼 \(C[2]=4\) 就是需要把 \(B\) 陣列 \(4\) 位置上的數換到 \(B\) 陣列的 \(2\) 位置上以與 \(A\) 陣列對應,而我們 \(B\) 陣列原來編號相當於 \(1,2,3,4\)。所以上文的使這個陣列單調遞增實際是反向操作。

還有一個坑了我挺久的點。先開始我沒有用 \(pos\) 陣列,直接令 \(c[a[i]]=b[i]\)

,得到了 \(10pts\) 的好成績。。。實際上我們排的是權值並不是陣列下標。

\(\text{Code}\)

#include <cstdio>

#define rep(i,_l,_r) for(register signed i=(_l),_end=(_r);i<=_end;++i)
#define fep(i,_l,_r) for(register signed i=(_l),_end=(_r);i>=_end;--i)
#define erep(i,u) for(signed i=head[u],v=to[i];i;i=nxt[i],v=to[i])
#define efep(i,u) for(signed i=Head[u],v=to[i];i;i=nxt[i],v=to[i])
#define print(x,y) write(x),putchar(y)

template <class T> inline T read(const T sample) {
	T x=0; int f=1; char s;
	while((s=getchar())>'9'||s<'0') if(s=='-') f=-1;
	while(s>='0'&&s<='9') x=(x<<1)+(x<<3)+(s^48),s=getchar();
	return x*f;
}
template <class T> inline void write(const T x) {
	if(x<0) return (void) (putchar('-'),write(-x));
	if(x>9) write(x/10);
	putchar(x%10^48);
}
template <class T> inline T Max(const T x,const T y) {if(x>y) return x; return y;}
template <class T> inline T Min(const T x,const T y) {if(x<y) return x; return y;}
template <class T> inline T fab(const T x) {return x>0?x:-x;}
template <class T> inline T Gcd(const T x,const T y) {return y?Gcd(y,x%y):x;}
template <class T> inline T Swap(T &x,T &y) {x^=y^=x^=y;}

#include <algorithm>
using namespace std;

const int maxn=1e5+5,mod=1e8-3;

int n,a[maxn],b[maxn],c[maxn],t[maxn],d[maxn],e[maxn];

int lowbit(int x) {return x&-x;}

void add(int x,int k) {
	while(x<=n) t[x]+=k,x+=lowbit(x);
} 

int ask(int x) {
	int r=0;
	while(x) (r+=t[x])%=mod,x-=lowbit(x);
	return r;
}

bool cmp(int x,int y) {return a[x]<a[y];}

bool Cmp(int x,int y) {return b[x]<b[y];}

int main() {
	int len,ans=0;
	n=read(9);
	rep(i,1,n) d[i]=i,a[i]=read(9);
	sort(d+1,d+n+1,cmp);
	rep(i,1,n) e[i]=i,b[i]=read(9);
	sort(e+1,e+n+1,Cmp);
	rep(i,1,n) c[d[i]]=e[i];
	fep(i,n,1) (ans+=ask(c[i]-1))%=mod,add(c[i],1);
	print(ans,'\n');
	return 0;
}