首页 > 其他分享 >NC24141 [USACO 2011 Dec G]Grass Planting

NC24141 [USACO 2011 Dec G]Grass Planting

时间:2023-06-23 17:33:41浏览次数:55  
标签:Planting hld int top USACO dep fat Dec assign

题目链接

题目

题目描述

Farmer John has N barren pastures (2 <= N <= 100,000) connected by N-1 bidirectional roads, such that there is exactly one path between any two pastures. Bessie, a cow who loves her grazing time, often complains about how there is no grass on the roads between pastures. Farmer John loves Bessie very much, and today he is finally going to plant grass on the roads. He will do so using a procedure consisting of M steps (1 <= M <= 100,000).
At each step one of two things will happen:
- FJ will choose two pastures, and plant a patch of grass along each road in between the two pastures, or,
- Bessie will ask about how many patches of grass on a particular road, and Farmer John must answer her question.
Farmer John is a very poor counter -- help him answer Bessie's questions!

输入描述

  • Line 1: Two space-separated integers N and M
  • Lines 2..N: Two space-separated integers describing the endpoints of a road.
  • Lines N+1..N+M: Line i+1 describes step i. The first character of the line is either P or Q, which describes whether or not FJ is planting grass or simply querying. This is followed by two space-separated integers Ai and Bi (1 <= Ai, Bi <= N) which describe FJ's action or query.

输出描述

  • Lines 1..???: Each line has the answer to a query, appearing in the
    same order as the queries appear in the input.

示例1

输入

4 6
1 4
2 4
3 4
P 2 3
P 1 3
Q 3 4
P 1 4
Q 2 4
Q 1 4

输出

2
1
2

题解

知识点:树链剖分,线段树。

通常树链剖分维护的是点权,但这里需要维护边权,因此我们考虑将边权映射到点权上,考虑用边的下端点代替一条边(上端点会导致非一对一映射)。

需要注意,更新操作时,对最后一段 \((u,v)\) 更新时,\(u\) 对应的那条边是不需要的,所以更新 \([L[u]+1,L[v]]\) 的点权。

时间复杂度 \(O((n+m)\log n)\)

空间复杂度 \(O(n)\)

代码

#include <bits/stdc++.h>
using namespace std;
using ll = long long;

struct HLD {
    vector<int> siz, dep, fat, son, top, dfn, L, R;

    HLD() {}
    HLD(int rt, const vector<vector<int>> &g) { init(rt, g); }

    void init(int rt, const vector<vector<int>> &g) {
        assert(g.size() >= rt + 1);
        int n = g.size() - 1;
        siz.assign(n + 1, 0);
        dep.assign(n + 1, 0);
        fat.assign(n + 1, 0);
        son.assign(n + 1, 0);
        top.assign(n + 1, 0);
        dfn.assign(n + 1, 0);
        L.assign(n + 1, 0);
        R.assign(n + 1, 0);

        function<void(int, int)> dfsA = [&](int u, int fa) {
            siz[u] = 1;
            dep[u] = dep[fa] + 1;
            fat[u] = fa;
            for (auto v : g[u]) {
                if (v == fa) continue;
                dfsA(v, u);
                siz[u] += siz[v];
                if (siz[v] > siz[son[u]]) son[u] = v;
            }
        };
        dfsA(rt, 0);

        int dfncnt = 0;
        function<void(int, int)> dfsB = [&](int u, int tp) {
            top[u] = tp;
            dfn[++dfncnt] = u;
            L[u] = dfncnt;
            if (son[u]) dfsB(son[u], tp);
            for (auto v : g[u]) {
                if (v == fat[u] || v == son[u]) continue;
                dfsB(v, v);
            }
            R[u] = dfncnt;
        };
        dfsB(rt, rt);
    }
};

template <class T>
class Fenwick {
    int n;
    vector<T> node;

public:
    Fenwick(int _n = 0) { init(_n); }

    void init(int _n) {
        n = _n;
        node.assign(n + 1, T());
    }

    void update(int x, T val) { for (int i = x;i <= n;i += i & -i) node[i] += val; }

    T query(int x) {
        T ans = T();
        for (int i = x;i >= 1;i -= i & -i) ans += node[i];
        return ans;
    }
};

struct T {
    int sum = 0;
    T &operator+=(const T &x) { return sum += x.sum, *this; }
};

const int N = 1e5 + 7;
vector<int> g[N];
HLD hld;
Fenwick<T> fw;

void path_update(int u, int v) {
    auto &top = hld.top;
    auto &dep = hld.dep;
    auto &fat = hld.fat;
    auto &L = hld.L;
    while (top[u] != top[v]) {
        if (dep[top[u]] < dep[top[v]]) swap(u, v);
        fw.update(L[top[u]], { 1 });
        fw.update(L[u] + 1, { -1 });
        u = fat[top[u]];
    }
    if (dep[u] > dep[v]) swap(u, v);
    fw.update(L[u] + 1, { 1 });
    fw.update(L[v] + 1, { -1 });
}

int main() {
    std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
    int n, m;
    cin >> n >> m;
    for (int i = 1;i <= n - 1;i++) {
        int u, v;
        cin >> u >> v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    hld.init(1, vector<vector<int>>(g, g + n + 1));

    fw.init(n);

    while (m--) {
        char op;
        cin >> op;
        if (op == 'P') {
            int u, v;
            cin >> u >> v;
            path_update(u, v);
        }
        else {
            int u, v;
            cin >> u >> v;
            if (hld.dep[u] < hld.dep[v]) swap(u, v);
            cout << fw.query(hld.L[u]).sum << '\n';
        }
    }
    return 0;
}

标签:Planting,hld,int,top,USACO,dep,fat,Dec,assign
From: https://www.cnblogs.com/BlankYang/p/17499415.html

相关文章

  • NC24048 [USACO 2017 Jan P]Promotion Counting
    题目链接题目题目描述Thecowshaveonceagaintriedtoformastartupcompany,failingtorememberfrompastexperiencethatcowsmaketerriblemanagers!Thecows,convenientlynumbered1…N(\(1\leqN\leq100,000\)),organizethecompanyasatree,withco......
  • [转]ubuntu20.04使用dev-sidecar找不到安装证书
    火狐、chrome等浏览器不走系统证书,火狐、谷歌浏览器必须在浏览器上安装证书然后死活找不到证书,搜索了整个目录也没有。原来是我的显示隐藏文件没打开。打开目录的“显示隐藏文件“的方法如下图所示:打开显示隐藏文件属性之后,dev-sidecar.ca.crt就出来了,如下图所示: ......
  • [USACO18DEC]Balance Beam P
    [USACO18DEC]BalanceBeamP热爱卡精度的你,为什么分数不取模?既然不去模,那么拿到这个题先想想能不能乱搞过去。设\(f_{i,j}\)表示\(i\)点出发至多走\(j\)次的最优期望报酬。当\(j\rightarrow+\infty\)时视为答案。转移为\[f_{i,j}=\max\{f_{i,j-1},\frac{f_{i......
  • Proj. CAR Paper Reading: Dire: A neural approach to decompiled identifier naming
    Abstract本文:工具:DIRE(DecompiledIdentifierRenamingEngine)任务:variablenamerecovery方法:使用词法和结构信息计算概率提出数据集:164632uniquex86-64binariesCprojsongithub实验效果:74.3%相符......
  • BigDecimal
    BigDecimal去一家公司笔试遇到一个这样的问题,问输出结果:BigDecimalbigDeciml1=newBigDecimal(2);BigDecimalbigDeciml2=newBigDecimal(2.1);BigDecimalbigDeciml3=newBigDecimal("2.1");结果:22.1000000000000000888178419700125232338905334472656252.1......
  • P1203 [USACO1.1]坏掉的项链Broken Necklace(C++_模拟_暴力枚举_优化)
    题目描述你有一条由n个红色的,白色的,或蓝色的珠子组成的项链,珠子是随意安排的。这里是n=29的两个例子:第一和第二个珠子在图片中已经被作记号。图片A中的项链可以用下面的字符串表示:brbrrrbbbrrrrrbrrbbrbbbbrrrrb假如你要在一些点打破项链,展开成一条直线,然后从一端开始收集......
  • Proj. CAR Paper Reading: Augmenting Decompiler Output with Learned Variable Name
    Abstract背景:decompilers难以恢复注释、variablenames,customvariabletypes本文:工具:DIRTY((DecompIledvariableReTYper)方法:postprocessesdecompiledfiles基于:Transformer训练数据:Github效果:实验:outperformspriorworkapproachesbyasizablemargin......
  • 'utf-8' codec can't decode byte 0xbc in position 1182: invalid start byte
    2.如果是字符集出现错误,建议多选择几种字符集测试一下:选择的经验是:如果是爬取到的网页文件,可以查看网页文件的meta标签下的charset属性值。例如:<metacharset="UTF-8">1也可以使用notepad++打开,查看下右下角的部位,会指示该文件是那种编码。 用一个例子来演示会更加清晰......
  • JavaScript的数学计算库:decimal.js
    Anarbitrary-precisionDecimaltypeforJavaScript.功能整数和浮点数简单但功能齐全的API复制JavaScript和对象的许多方法Number.prototypeMath还处理十六进制、二进制和八进制值比Java的BigDecimalJavaScript版本更快,更小,也许更容易使用无依赖关系广泛的平......
  • python: encode and decode
    importbinasciigeovin=b"geovindu"adu=base64.b64encode(geovin)#加密码print(adu)edu=base64.b64decode(adu)#解密print(edu)s=["医疗",400,1]column=('InsuranceName','InsuranceCost'......