《算法竞赛进阶指南》学习笔记

· · 个人记录

luogu P10453 七夕祭

我认为这道题很妙的地方在于,将问题抽象成环形均分纸牌模型之后,通过分析找到了与普通的均分纸牌的区别;
在进行一些转化之后,将代数的问题转化成等价的几何模型,即货舱选址问题,从而较为方便的求得答案。
真的是一道很妙的题,可以看看旧版蓝书 P33-34 页的分析。 ::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

const int N = 1e5 + 10;
int n, m, t, row[N], col[N];
typedef long long ll;

ll solve(int x, int a[]){
    int b[N], c[N], sum = 0, avg;
    for(int i = 1; i <= x; i ++) sum += a[i];
    if(sum % x) return -1;
    avg = sum / x;
    for(int i = 1; i <= x; i ++) b[i] = a[i] - avg;
    c[1] = 0;
    for(int i = 1; i <= x; i ++) c[i] = c[i - 1] + b[i];
    sort(c + 1, c + x + 1);
    ll res = 0, tar = c[(x + 1)/2];
    for(int i = 1; i <= x; i ++) res += abs(c[i] - tar);
    return res;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m >> t;
    int x, y;
    for(int i = 1; i <= t; i ++){
        cin >> x >> y;
        row[x] ++, col[y] ++;
    }

    ll res_r = solve(n, row);
    ll res_c = solve(m, col);

    if(res_r != -1 && res_c != -1) cout << "both " << res_c + res_r << endl;
    else if(res_r != -1) cout << "row " << res_r << endl;
    else if(res_c != -1) cout << "column " << res_c << endl;
    else cout << "impossible" << endl;

    return 0;
}

::::

luogu P10455 Genius ACM
这个 check 函数很类似于二分,但当 k 很小时,二分的时间复杂度可能会退化,而 T 很大,所以可能无法通过此题。
倍增则是通过二进制划分,保证对于多大的 k,复杂度都在 log 左右。 第一次对倍增思想有这样的理解。
自认为没有讲的很好的题解,多看看题自己理解一下吧。 ::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

const int N = 5e5 + 10;
typedef long long ll;
int lg[N];
ll k;
int T, n, m;
int tmp[N], a[N], sol[N];


bool check(int l, int mid, int r){
    if(r > n) return false;
    for(int i = mid; i <= r; i ++) sol[i] = a[i];
    sort(sol + mid, sol + r + 1);
    merge(sol + l, sol + mid, sol + mid, sol + r + 1, tmp + l);
    ll sum = 0;
    int L = l, R = r, cnt = 0;
    while(l < r && ++cnt <= m){
        //贪心的选择最大的点看是否符合要求
        sum += (ll)(tmp[r] - tmp[l]) * (tmp[r] - tmp[l]);
        l ++, r --;
    }
    if(sum <= k) for(int i = L; i <= R; i ++) sol[i] = tmp[i];
    return sum <= k;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    for(int i = 2; i < N; i ++) lg[i] = lg[i >> 1] + 1;
    cin >> T;
    while(T--){
        cin >> n >> m >> k;
        for(int i = 1; i <= n; i ++) cin >> a[i];
        int res = 0;
        int l, r, b;
        l = r = b = 1;
        sol[l] = a[l];
        while(r <= n){
            if(b == 0){
                l = r + 1;
                r = l;
                res ++;
            }
            if(check(l, r + 1, r + (1 << b) - 1)){
                r = r + (1 << b) - 1;
                b ++;
            }else b --;
        }
        cout << res << endl;
    }

    return 0;
}

:::: luogu P1842 奶牛玩杂技
在此之前一直是不知道贪心到底该怎么证明的。以此题为例来证明一下吧。
此题的贪心策略是 w+s 较大的排在下面。
考虑使用邻项交换法证明。

设 w_a+s_a>w_b+s_b,且 a 与 b 相邻,两头牛上面的牛的总重设为 w。

当 a 在上,b 在下时:

a$ 的压扁指数为 $w-s_a$,$b$ 为 $w+w_a-s_b

因为 w_a+s_a>w_b+s_b
那么 w_a-s_b>w_b-s_a
因为 w_b\ge 0,所以 w_a - s_b > -s_a
所以 w+(w_a-s_b) > w - s_a,即当 a 在上时,总压扁指数为 w + w_a - s_b(不考虑上面的牛的压扁指数)

$a$ 的指数为 $w + w_b - s_a b$ 的指数为 $w - s_b

因为 w_a + s_a > w_b + s_b
所以 w_b - s_a < w_a - s_b
又因为 w_a > 0
所以 w_b - s_a < -s_b
所以 w + (w_b - s_a) < w + (-s_b),所以当 b 在上时,总压扁指数为 w - s_b(不考虑上面的牛的压扁指数)

综上,a 在下面更优,即力量加体重大的在下面比在上面更优。

注意到我们前面的分讨,都假设不考虑上面的牛的情况。
那么,若上面牛的总压扁指数比 a 的最优情况大,那么把 a 排在下面也不会变差;
如果不如当前大的话,a 排在下面是更优的情况。
综上,我们证明了将 w+s 更大的排在下面更优。 ::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

const int N = 5e4 + 10;
int n;
struct node{
    int w, s;
    bool operator < (const node &t)const{
        return w + s < t.w + t.s;
    }
}a[N];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    for(int i = 1; i <= n; i ++){
        cin >> a[i].w >> a[i].s;
    }
    sort(a + 1, a + n + 1);
    int w = 0, res = -1e9;
    for(int i = 1; i <= n; i ++){
        res = max(res, w - a[i].s);
        w += a[i].w;
    }
    cout << res << endl;

    return 0;
}

:::: luogu P2827 蚯蚓
此题启发我们,从一些特殊情况出发,逐步推导出正解的思路。例如,在此题中,q=0 的解法很好想,进而我们可以推导出将 q 单独维护的想法。
除此以外,将较难维护的信息(如本题的 q)换一种方式维护,以及正难则反,都是一些常见的思考方式。
这篇题解的思路解释和结论证明写得很好,可以参考。 ::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

typedef long long ll;
const ll N = 1e5 + 10, inf = 1e18;
ll n, m, q, u, v, t;
queue<ll> a[3];
ll inp[N];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n >> m >> q >> u >> v >> t;
    for(int i = 1; i <= n; i ++) cin >> inp[i];
    sort(inp + 1, inp + n + 1);
    for(int i = n; i >= 1; i --) a[0].push(inp[i]);
    for(int i = 1; i <= m; i ++){
        ll tp = -inf, idx;
        for(int j = 0; j < 3; j ++) if(!a[j].empty() && a[j].front() > tp) tp = a[j].front(), idx = j;
        a[idx].pop();
        tp += 0ll + (i - 1) * q;
        ll tx = tp * u / v, ty = tp - tx;
        if(i % t == 0) cout << tp << " ";
        a[1].push(tx - i * q); a[2].push(ty - i * q);
    }
    cout << endl;
    for(int i = 1; i; i ++){
        ll tp = -inf, idx;
        for(int j = 0; j < 3; j ++) if(!a[j].empty() && a[j].front() > tp) tp = a[j].front(), idx = j;
        if(tp == -inf) break;
        a[idx].pop();
        if(i % t == 0) cout << tp + m * q << " ";
    }

    return 0;
}

::::

luogu P9350 JOI2023Final 宣传 2
此题较为关键的就是拆绝对值式。
观察 |X_i - X_j| \le E_i - E_j 这一式子,遇到绝对值我们先拆绝对值。

对于任意实数 a 和 b\ge 0,有:

|a|\le b \iff -b\le a\le b \iff a\le b \ \text{且}\ -a\le b

令

a=X_i-X_j,\qquad b=E_i-E_j

则

|X_i-X_j|\le E_i-E_j

等价于

-(E_i-E_j)\le X_i-X_j\le E_i-E_j

拆开就是:

X_i-X_j\le E_i-E_j

并且

X_j-X_i\le E_i-E_j

也即

E_j-X_j\le E_i-X_i 且 X_j+E_j\le X_i+E_i

那么在拆开式子之后,该如何做呢? 和前面的 “逛庙会” 类似的思路,我们不妨把这个较难求解的代数问题转化为几何问题。
我们令 E-X 为横坐标, E+X 为纵坐标,不难发现一个居民影响的范围就是这个点和原点构成的矩形(离散化后)。 我们还可以发现,从左到右看,选取的点的纵坐标是单调递减的,因为如果某个点右上方还有一个点,我们会直接选择那个点而放弃当前点。
按照纵坐标从上往下扫,如果一个点的横坐标大于目前扫过的最大的横坐标时,会对答案产生贡献。

::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

const int N = 5e5 + 10;
int n;
struct node{
    int x, y;
    bool operator < (const node &t)const{
        if(x == t.x) return y > t.y;
        return x > t.x;
    }
}a[N];
int lst = -1e9;

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    int x, y;
    for(int i = 1; i <= n; i ++){
        cin >> x >> y;
        a[i].x = x + y;
        a[i].y = y - x;
    }
    sort(a + 1, a + n + 1);
    int res = 0;
    for(int i = 1; i <= n; i ++){
        if(a[i].y > lst) res ++, lst = a[i].y; 
    }
    cout << res << endl;

    return 0;
}

:::: 字符串 Hash 板子题
不多赘述了,记一下板子。
此外,结合这道题,我们再记录一下如何在 O(N) 预处理前缀 Hash 值之后,O(1) 计算任意字串的 Hash 值。

如果我们已知字符串 S 的 Hash 值为 H(S),那么在 S 后添加一个字符 c 构成的字符串 S+c 的 Hash 值即为 H(S+c)=(H(s)\times P+val_c)\mod M,其中 P,M 分别为为我们选定的大质数和模数,val_c 表示我们为 c 选定的代表数值。

如果我们已知H(S),H(S+T),其中 S,T 均为字符串,则 H(T)=(H(S+T)-H(S)*P^{\operatorname{length(T)}})\mod M。这就相当于通过 P 进制下在 S 后边补 0 的形式,把 S 左移到与 S+T 的左端对齐,然后二者相减就得到了 H(T) ::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

const int P = 131, N = 1e6 + 10;
string s;
int n, q;
unsigned long long p[N], h[N];

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> s;
    s = '0' + s;
    n = s.length() - 1;
    cin >> q;
    p[0] = 1;
    for(int i = 1; i <= n; i ++){
        h[i] = h[i - 1] * 131 + (s[i] - 'a' + 1);
        p[i] = p[i - 1] * 131;
    }
    int l1, l2, r1, r2;
    while(q --){
        cin >> l1 >> r1 >> l2 >> r2;
        if(h[r1] - h[l1 - 1] * p[r1 - l1 + 1] == h[r2] - h[l2 - 1] * p[r2 - l2 + 1]) cout << "Yes" << endl;
        else cout << "No" << endl;
    }

    return 0;
}

::::

P4551 最长异或路径
很玄妙的思路,注意到两点之间路径的异或等同于两点到根的路径的异或再异或起来,因为 LCA 到根之间的路径被异或了两次,贡献被抵消。然后再把距离转化成二进制,构建一颗 Trie 树贪心的选最高位即可。 ::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
//#define endl '\n'
using namespace std;

const int N = 3.2e6 + 10;
struct node{
    int son[2];
}tr[N];
struct edge{
    int v, nxt, w;
}eg[N];
int hd[N], cntt;
int n, res, cnt = 1;
int d[N];

inline void add(int x, int y, int z){
    cntt++;
    eg[cntt] = {y, hd[x], z};
    hd[x] = cntt;
}

void dfs(int nw, int fa){
    for(int i = hd[nw]; i; i = eg[i].nxt){
        int to = eg[i].v;
        if(to == fa) continue;
        d[to] = d[nw] ^ eg[i].w;
        dfs(to, nw);
    } 
}

string to_s(int x){
    string s = "";
    for(int i = 31; i >= 0; i --){
        int v = (x >> i) & 1;
        s.push_back(v + '0');
    }
    return s;
}

void insert(string s){
    int nw = 1;
    for(int i = 0; i < 32; i ++){
        int v = s[i] - '0';
        if(!tr[nw].son[v]) tr[nw].son[v] = ++cnt;
        nw = tr[nw].son[v];
    }
}

int query(string s){
    long long ans = 0, nw = 1;
    for(int i = 0; i < 32; i ++){
        int v = s[i] - '0';
        v ^= 1;
        if(tr[nw].son[v]) nw = tr[nw].son[v], ans += (1ll << (31 - i));
        else nw = tr[nw].son[v ^ 1];
    }
    return ans;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    int x, y, z;
    for(int i = 1; i < n; i ++){
        cin >> x >> y >> z;
        add(x, y, z);
        add(y, x, z);
    }
    dfs(1, 0);
    for(int i = 1; i <= n; i ++){
        string tar = to_s(d[i]);
        if(i > 1) res = max(res, query(tar));
        insert(tar);
    }
    cout << res << endl;
    return 0;
}

:::: P14374 [JOISC 2018] 糖果 / Candies
反悔贪心板子题。如果之前没见过的话可能确实是有点难想到的,具体请参考这篇题解,讲的还是不错的。
大体思路就是,先贪心的选,然后把反悔的选项插入成为下一次的可选项,例如这道题,每次贪心地选最大的,然后把选两边而不选中间的选项插入选择队列。
::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
#define int long long
using namespace std;

const int N = 5e5 + 10;
struct node{
    int val, idx;
    bool operator <(const node &t)const{
        return val < t.val;
    }
};
priority_queue<node> q;
struct qwq{
    int l, r, val;
}a[N];
int n, m, lst, res;
bool vis[N];

void del_lr(int idx){
    int L = a[idx].l, R = a[idx].r;
    a[idx].l = a[L].l, a[idx].r = a[R].r;
    a[a[idx].l].r = idx, a[a[idx].r].l = idx;
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    int x;
    for(int i = 1; i <= n; i ++){
        cin >> x;
        a[i].val = x, a[i].l = i - 1, a[i].r = i + 1;
        q.push({x, i});
    }
    a[0].val = a[n + 1].val = -1e18;
    m = n / 2 + (n % 2);
    for(int i = 1; i <= m; i ++){
        while(vis[q.top().idx]) q.pop();
        node nw = q.top();
        q.pop();
        res += nw.val;
        vis[a[nw.idx].l] = vis[a[nw.idx].r] = true;
        a[nw.idx].val = a[a[nw.idx].l].val + a[a[nw.idx].r].val - a[nw.idx].val;
        q.push({a[nw.idx].val, nw.idx});
        del_lr(nw.idx);
        cout << res << endl;
    }

    return 0;
} 

::::

NOIP 2004 提高组 合并果子 加强版

过早的优化是万恶之源

注意到此题需要 O(N) 的时间复杂度求解。本题 O(\log n) 的做法此处不再给出,很好想,可以去参看一下题解。
接下来考虑算法的低效部分在哪里。\log 的做法需要排序和优先队列,考虑一下如何规避。
首先,我们发现 a_i\le 10^5,于是可以用桶排代替快排。
另外,对于优先队列,我们需要的就是插入操作,以及查询最小值;此外,此题容易发现一个性质,就是插入的数单调递增。于是可以用一个类似于“堆顶队列”的办法来实现,用两个队列分别存储原值和插入值,然后在两个队头中选择较小的返回即可。
::::info[code]

#include<bits/stdc++.h>
#define debug() cout<<"_Liyx_ is tangwang"<<endl
#define endl '\n'
using namespace std;

typedef long long ll;
const int M = 1e5 + 10;
int n, x, cnt[M];
ll res;
queue<ll> q1, q2;

inline ll getmin(){
    ll t;
    if(q2.empty() || (!q1.empty() && q1.front() < q2.front())){
        t = q1.front();
        q1.pop();
    }else{
        t = q2.front();
        q2.pop();
    }
    return t;
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0), cout.tie(0);

    cin >> n;
    for(int i = 1; i <= n; i ++) cin >> x, cnt[x] ++;
    for(int i = 1; i < M; i ++) for(int j = 1; j <= cnt[i]; j ++) q1.push(i);
    for(int i = 1; i < n; i ++){
        ll x = getmin(), y = getmin();
        res += x + y;
        q2.push(x + y);
    }
    cout << res << endl;

    return 0;
}

::::