2021牛客暑期多校训练营3 B.Black and white 最小生成树

Posted kaka0010

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2021牛客暑期多校训练营3 B.Black and white 最小生成树相关的知识,希望对你有一定的参考价值。

原题链接:https://ac.nowcoder.com/acm/contest/11254/B

题意

你需要将n*m的矩阵全部变成黑色(初始为白色),每个点都有一个花费,并且如果任意一个矩阵的三个顶点为黑,那么剩下那个顶点自动变黑,问最小的花费。

分析

根本就没往图这方面想,题目还是具有很大的欺骗性。如果自己手画一下的话,很容易发现其实最少只要涂n+m-1个点就可以了,再与行和列联系一下,不就是以行列为点的最小生成树吗?

我们再仔细分析一下,如果(x1,y1)(x2,y2)(x1,y2)有边,那么(x2,y2)自然在一个连通块里了,因此用最小生成树就可以解决问题。建议用桶排序的kruskal或直接上prim,2e7的范围sort还是容易tle的。

Code

#include <bits/stdc++.h>
#define lowbit(i) i & -i
#define Debug(x) cout << x << endl
#define fi first
#define se second
using namespace std;
typedef long long ll;
typedef pair<int, int> PII;
const ll INF = 1e18;
const int N = 1e5 + 10;
const int M = 1e6 + 10;
const int MOD = 998244353;
int n, m, a, b, c, d, p;

int A[5005*5005], mp[5005][5005], fa[5005*2];
vector<PII> g[N];
int find(int x) {return x == fa[x] ? x : fa[x] = find(fa[x]);}
void solve() {
    cin >> n >> m >> a >> b >> c >> d >> p;
    A[0] = a;
    for (int i = 1; i <= n*m; i++) {
        A[i] = (A[i-1] * A[i-1] * b + A[i-1] * c + d) % p;
    }
    for (int i = 1; i <= n+m; i++) fa[i] = i;
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            mp[i][j] = A[(i-1)*m+j];
            g[mp[i][j]].push_back({i, j+n});
        }
    }
    ll ans = 0;
    for (int i = 0; i <= 100000; i++) {
        if (!g[i].size()) continue;
        for (auto it : g[i]) {
            int u = it.fi;
            int v = it.se;
            int fu = find(u);
            int fv = find(v);
            if (fu != fv) {
                fa[fu] = fv;
                ans += i;
            }
        }
    }
    cout << ans << endl;
}
signed main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
#ifdef ACM_LOCAL
    freopen("input", "r", stdin);
    freopen("output", "w", stdout);
    signed test_index_for_debug = 1;
    char acm_local_for_debug = 0;
    do {
        if (acm_local_for_debug == '$') exit(0);
        if (test_index_for_debug > 20)
            throw runtime_error("Check the stdin!!!");
        auto start_clock_for_debug = clock();
        solve();
        auto end_clock_for_debug = clock();
        cout << "Test " << test_index_for_debug << " successful" << endl;
        cerr << "Test " << test_index_for_debug++ << " Run Time: "
             << double(end_clock_for_debug - start_clock_for_debug) / CLOCKS_PER_SEC << "s" << endl;
        cout << "--------------------------------------------------" << endl;
    } while (cin >> acm_local_for_debug && cin.putback(acm_local_for_debug));
#else
    solve();
#endif
    return 0;
}

以上是关于2021牛客暑期多校训练营3 B.Black and white 最小生成树的主要内容,如果未能解决你的问题,请参考以下文章

2021牛客暑期多校训练营3

2021牛客暑期多校训练营1 - F - Find 3-friendly Integers - 题解

2021牛客暑期多校训练营1 - F - Find 3-friendly Integers - 题解

2021牛客暑期多校训练营 3

2021牛客暑期多校训练营1

2021牛客暑期多校训练营1