[JZOJ5405]Permutation

来源:互联网 发布:淘宝唯一店铺号选靓号 编辑:程序博客网 时间:2024/06/15 03:05

问题描述

你有一个长度为n 的排列P 与一个正整数K
你可以进行如下操作若干次使得排列的字典序尽量小
对于两个满足|i-j|>=K 且|Pi-Pj| = 1 的下标i 与j,交换Pi 与Pj
对于前20% 的数据满足n <= 6
对于前50% 的数据满足n <= 2000
对于100% 的数据满足n <= 500000

分析

我有个没有正确性也没有复杂度的水法….能拿90。
国外的题能够刷新脑回路…
我们看他位置这么远,转换一下,就变成相邻交换了。
设pos[p[i]]=i,那么就是相邻两个如果|pos[i]-pos[i±1]|>=K就可以交换pos值了嘛。
原题就变成了让pos靠前的值尽量小,其实也就是你按p[i]从小到大考虑能不能往前放。那么考虑贪心,我们先把pos值1移到尽量前,那么只能移动到第一个|pos[x]1|<K就不能移了嘛,即最终pos[x+1]=1。
对于2,3,4…也是一样的,并且,碰到pos[x]<当前值,我们也不移动,这贪心嘛。O(n2)
然后我们可以继续开脑洞,考虑最初位置为1的点为y,那么我们连有向边边(pos[x],pos[y]),表示pos[y]不能超过pos[x],对于每个y,我们都枚举x,连边。最后会形成一个DAG,那么我们只要寻找一种字典序最小的拓扑序即可,因为入度为0的点,代表他可以移动到最前面(还是在移动过的点的后面)。最后转换回原来序列输出即可。
我们发现边的数量并不多,但是找边找很久,我们可以用数据结构。那么对于pos[x],我们找到他后面下标最小的y,满足|pos[x]pos[y]|<K的点,连(pos[x],pos[y])。两个限制,求最小值,可以让一个量单调枚举,另一个用set或者线段树查询即可。具体地,绝对值先拆开,我们按pos[x]从大到小和从小到大都枚举一次,即n~1和1~n,然后在set里面维护pos[x]±K范围内的pos下标值,然后再找出大于当前枚举x的最小下标y,连边即可。
nlogn做完了。

代码

#include<cstdio>#include<algorithm>#include<cmath>#include<cstring>#include<set>#include<bitset>using namespace std;#define fo(i,j,k) for(i=j;i<=k;i++)#define fd(i,j,k) for(i=j;i>=k;i--)#define cmax(a,b) (a=(a>b)?a:b)typedef long long ll;typedef double db;const int N=1e6+5,s=131,mo=1e8;multiset<int> tr;multiset<int> :: iterator it;int a[N],pos[N],n,K,i,j,rev[N],prt[N],ru[N],c[N];int tt,b[N],nxt[N],first[N];void cr(int x,int y){    tt++;    b[tt]=y;    c[tt]=x;    nxt[tt]=first[x];    first[x]=tt;}int main(){    freopen("t2.in","r",stdin);    freopen("t2.out","w",stdout);    scanf("%d %d",&n,&K);    fo(i,1,n) scanf("%d",a+i),pos[a[i]]=i;    fo(i,1,n)    {        if (i-K>0) tr.erase(tr.find(a[i-K]));        it=tr.lower_bound(a[i]);        if (it!=tr.end())            cr(i,pos[(*it)]),ru[pos[(*it)]]++;        tr.insert(a[i]);    }    tr.clear();    fd(i,n,1)    {        if (i+K<=n) tr.erase(tr.find(a[i+K]));        it=tr.lower_bound(a[i]);        if (it!=tr.end())            cr(pos[a[i]],pos[(*it)]),ru[pos[(*it)]]++;        tr.insert(a[i]);    }    tr.clear();    fo(i,1,n) if (!ru[i]) tr.insert(i);    while (!tr.empty())    {        rev[++rev[0]]=*tr.begin();        tr.erase(tr.begin());        for (int p=first[rev[rev[0]]];p;p=nxt[p])            if (!(--ru[b[p]])) tr.insert(b[p]);    }    fo(i,1,n) prt[rev[i]]=i;    fo(i,1,n) printf("%d\n",prt[i]);}
原创粉丝点击