题解:P11244 吻秋

· · 题解

洛谷 [P11244] 吻秋 题解

前置步骤

首先,我们会发现一个有趣的结论:“有用的”操作数量一定 \le m^2。
从对“有用的”操作的定义出发,感性证明一下:一次“有用的”操作结束后,我们都会得到两个新的有序序列,同时 \forall u \in a_x 必定小于等于 \forall v \in a_y,相当于我们得到一组新的偏序关系。而得到 m^2 组偏序关系后,这些序列就被唯一确定下来了,不会再发生新的变动。
该结论对于我们无疑是一种鼓舞,它昭示着我们只需要进行至多 nm^2 次“有用的”操作,即可回答所有的询问,而不是 qn 此等巨大的时间复杂度。

接下来,我们思考,如何判断此次操作是不是“有用的”?如果操作是“有用的”,我们应该怎样处理?如果操作不是“有用的”,我们又应该怎样处理?不要着急,让我们分情况进行逐步分析、分类讨论:

询问操作则相对简单,直接找到当前标号所对应的序列 a_i,查找其的第 j 个元素 a_{i,j} 即可。(此处的时间复杂度显然是 O(q) 的。)

代码参考

在我的代码中,rt_x 代表标号 x 真正对应的序列编号;fp_x 代表编号为 x 的序列是否是首次操作;vec 则是存储的序列;其余均无大碍,不影响代码的阅读。另外,在我的代码中,n 代表序列数量,m 代表序列长度,与题目描述恰好相反,请注意区分:

#include<bits/stdc++.h>
#define N 2000009
char buf[1 << 21], *p1 = buf, *p2 = buf;
#define getchar() (p1 == p2 && (p1 = buf, p2 = (p1 + fread(buf, 1, 1 << 21, stdin))) == p1 ? EOF : *p1++)
template <typename T> inline T read() { T x = 0, w = 0; char ch = getchar(); while (ch < '0' || ch > '9') w |= (ch == '-'), ch = getchar(); while ('0' <= ch && ch <= '9') x = x * 10 + (ch ^ '0'), ch = getchar(); return w ? -x : x; }
template <typename T> inline void write(T x) { if (!x) return; write<T>(x / 10), putchar((x % 10) ^ '0'); }
template <typename T> inline void print(T x) { if (x > 0) write<T>(x); else if (x < 0) putchar('-'), write<T>(-x); else putchar('0'); }
template <typename T> inline void print(T x, char en) { print<T>(x), putchar(en); }
using namespace std;
int n,m,T,op,x,y,rt[N],fp[N];
vector<int>vec[N];
void msort(int u,int v)
{
    if(!fp[rt[u]]) sort(vec[rt[u]].begin(),vec[rt[u]].end()),fp[rt[u]]=1;
    if(!fp[rt[v]]) sort(vec[rt[v]].begin(),vec[rt[v]].end()),fp[rt[v]]=1;
    int ls=vec[rt[u]][vec[rt[u]].size()-1];
    int rs=vec[rt[v]][vec[rt[v]].size()-1];
    if(ls<=vec[rt[v]][0]) return;
    else if(rs<=vec[rt[u]][0]) swap(rt[u],rt[v]);
    else 
    {
        vector<int>mp(2*m);
        merge(vec[rt[u]].begin(),vec[rt[u]].end(),vec[rt[v]].begin(),vec[rt[v]].end(),mp.begin());
        vec[rt[u]].clear(),vec[rt[v]].clear();
        for(int i=0;i<m;i++) vec[rt[u]].push_back(mp[i]);
        for(int i=m;i<2*m;i++) vec[rt[v]].push_back(mp[i]);     
    }
}
int main()
{
    m=read<int>(),n=read<int>(),T=read<int>();
    memset(fp,0,sizeof(fp));
    for(int i=1;i<=n;i++)
    for(int j=1;j<=m;j++)
    {
        x=read<int>(),vec[i].push_back(x);
    }
    for(int i=1;i<=n;i++) rt[i]=i;
    while(T--)
    {
        op=read<int>(),x=read<int>(),y=read<int>();
        if(op==1) msort(x,y);
        else print(vec[rt[x]][y-1],'\n');
    }
    return 0;
}

注意到该代码的时间复杂度是 O(mn \log{n}+nm^2+q),空间复杂度是 O(nm),可以通过本题的数据。感谢您的阅读,愿我们在未来的OI之路上都能学有所成。