Codeforces Round #286 (Div. 1) D. Mr. Kitayuta's Colorful Graph

Posted cjlhy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Codeforces Round #286 (Div. 1) D. Mr. Kitayuta's Colorful Graph相关的知识,希望对你有一定的参考价值。

D - Mr. Kitayuta‘s Colorful Graph

思路:我是暴力搞过去没有将答案离线,感觉将答案的离线的方法很巧妙。。

对于一个不大于sqrt(n) 的块,我们n^2暴力枚举, 对于大于sqrt(n)的块,我们暴力枚举答案。

这样就能做到严格sqrt(n) * n

#include<bits/stdc++.h>
#define LL long long
#define fi first
#define se second
#define mk make_pair
#define PII pair<int, int>
#define y1 skldjfskldjg
#define y2 skldfjsklejg

using namespace std;

const int N = 1e5 + 7;
const int inf = 0x3f3f3f3f;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1e9 + 7;

int n, m, cnt, fa[N], a[N], b[N], c[N];
unordered_map<int, bool> mp[N];
map<PII, int> ans;
vector<PII> vec[N];
int getRoot(int x) {
    return fa[x] == x ? x : getRoot(fa[x]);
}

int main() {
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++) {
        scanf("%d%d%d", &a[i], &b[i], &c[i]);
        vec[c[i]].push_back(mk(a[i], b[i]));
    }
    for(int i = 1; i <= n; i++) fa[i] = i;
    for(int i = 1; i <= m; i++) {
        map<int, int> ma;
        for(PII t : vec[i]) {
            int x = getRoot(t.fi), y = getRoot(t.se);
            if(x != y) fa[x] = y;
        }
        for(PII t : vec[i]) {
            int x = getRoot(t.fi), y = getRoot(t.se);
            if(ma.find(x) != ma.end()) {
                mp[t.fi][ma[x]] = true;
            } else {
                cnt++;
                mp[t.fi][cnt] = true;
                ma[x] = cnt;
            }
            if(ma.find(y) != ma.end()) {
                mp[t.se][ma[y]] = true;
            } else {
                cnt++;
                mp[t.se][cnt] = true;
                ma[y] = cnt;
            }
        }
        for(PII t : vec[i]) {
            fa[t.fi] = t.fi;
            fa[t.se] = t.se;
        }
    }

    int q; scanf("%d", &q);
    while(q--) {
        int u, v;
        scanf("%d%d", &u, &v);
        if(mp[u].size() > mp[v].size()) swap(u, v);
        if(ans.find(mk(u, v)) != ans.end()) {
            printf("%d
", ans[mk(u, v)]);
        } else {
            int num = 0;
            for(auto t : mp[u]) {
                if(mp[v].find(t.fi) != mp[v].end()) num++;
            }
            printf("%d
", num);
            ans[mk(u, v)] = num;
        }
    }
    return 0;
}

/*
*/

 

以上是关于Codeforces Round #286 (Div. 1) D. Mr. Kitayuta's Colorful Graph的主要内容,如果未能解决你的问题,请参考以下文章

Codeforces Round #436 E. Fire(背包dp+输出路径)

[ACM]Codeforces Round #534 (Div. 2)

Codeforces Round #726 (Div. 2) B. Bad Boy(贪心)

Codeforces Global Round 19

Codeforces Educational Codeforces Round 67

Codeforces Round 1132Educational Round 61