跳到正文

题解

P8097 [USACO22JAN] Farm Updates G

耶梦加得约 5 分钟
原文
文章信息与版本

文章信息

发布
2022年2月7日
收录
2026年7月12日
更新
2026年11月10日
篇幅
约 5 分钟
获赞
21
题目
P8097

版本

  1. v1当前

容易想到倒着做,问题在于本题还有 Add 操作,怎么处理?

不处理。

题目有一条限制是只会在两个活跃的农场中间添加道路我就是没看到这个保龄了,这就意味着我们在倒着操作的过程中,删去这条边不会导致任何农场失活,换而言之,在倒着操作的过程中不会有任何农场失活。

先正着记录下每条边最终的状态(连接与否)和每个农场最后的状态,然后遍历整张图计算出此刻哪些农场是活跃的,最后倒着操作,遇到 Delete 就改一下状态再从这个点出发遍历联通块,遇到 Remove 就加边,如果至少有一个端点是活跃的,就从它出发再遍历联通块。

实现上,由于不会有农场失活,一旦激活就不需要再次遍历,用一个 vis 数组记录是否激活过这个点。每个点最多被激活一次,因此 dfs 复杂度为 O(N)O(N),总复杂度 O(N+Q)O(N + Q)。

答案可以在 dfs 的过程中顺便更新。

C++
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
int n, m;
char ch[7];
int ans[100007];
int act[100007]; //农场活跃与否
pair<int, int> e[200007];
int eid; 
int stat[200007]; //边是否断开,断开为0,连接为1
pair<int, int> q[200007];
vector<int> g[100007];
bool vis[100007];
void dfs(int x, int t) { //t 代表操作时间
    vis[x] = 1; if(!ans[x]) ans[x] = t; //最后一个活跃的时刻,对于倒序操作就是第一个
    for(int i = 0; i < g[x].size(); ++i) {
        int to = g[x][i];
        if(vis[to]) continue;
        act[to] |= act[x];
        dfs(to, t);
    }
} //易知不存在一个点被遍历过却没有激活
signed main() {
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; ++i) act[i] = 1;
    for(int i = 1; i <= m; ++i) {
        scanf("%s", ch + 1); 
        int x, y;
        switch(ch[1]) {
        case 'A' :
            scanf("%d %d", &x, &y);
            e[++eid] = make_pair(x, y);
            stat[eid] = 1;
            break;
        case 'R' :
            scanf("%d", &x);
            q[i] = make_pair(1, x);
            stat[x] = 0;
            break;
        case 'D' :
            scanf("%d", &x);
            act[x] = 0;
            q[i] = make_pair(2, x);
            break;
        }
    }
    for(int i = 1; i <= eid; ++i) {
        if(stat[i]) {
            g[e[i].first].push_back(e[i].second);
            g[e[i].second].push_back(e[i].first);
        }
    }
    for(int i = 1; i <= n; ++i) {
        if(act[i] && !vis[i]) dfs(i, m);
    }
    for(int i = m; i; --i) {
        int x, y;
        switch(q[i].first) {
        case 1:
            x = e[q[i].second].first, y = e[q[i].second].second;
            g[x].push_back(y);
            g[y].push_back(x);
            if(act[x]) dfs(x, i - 1);
            if(act[y]) dfs(y, i - 1);
            break;
        case 2:
            x = q[i].second;
            act[x] = 1;
            dfs(x, i - 1);
            break;
            //A操作不管
        }
    }
    for(int i = 1; i <= n; ++i) printf("%d\n", ans[i]);
    return 0;
}
原文
存档评论4 条抓取于