栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【PAT A-1013】Battle Over Cities

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【PAT A-1013】Battle Over Cities

【PAT A-1013】Battle Over Cities C++代码

方法一:深搜

// DFS 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
#include
using namespace std;
using gg = long long;
const gg MAX = 1005;
vector> graph(MAX);
vector visit(MAX);
void dfs(gg v) {
    visit[v] = true;
    for (gg i : graph[v]) {
        if (not visit[i]) {
            dfs(i);
        }
    }
}
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    gg ni, mi, ki, ai, bi;
    cin >> ni >> mi >> ki;
    for (gg i = 0; i < mi; ++i) {
        cin >> ai >> bi;
        graph[ai].push_back(bi);
        graph[bi].push_back(ai);
    }
    while (ki--) {
        cin >> ai;
        fill(visit.begin(), visit.begin() + ni + 1, false);
        visit[ai] = true;
        gg num = 0;
        for (gg i = 1; i <= ni; ++i) {
            if (not visit[i]) {
                ++num;
                dfs(i);
            }
        }
        cout << num - 1 << "n";
    }
    return 0;
}

方法二:并查集

//并查集
#include 
using namespace std;
using gg = long long;
const gg MAX = 1005;
vector ufs(MAX);
void init() { iota(ufs.begin(), ufs.end(), 0); }
gg findRoot(gg x) { return ufs[x] == x ? x : ufs[x] = findRoot(ufs[x]); }
void unionSets(gg a, gg b) { ufs[findRoot(a)] = findRoot(b); }
int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);
    gg ni, mi, ki, ai;
    cin >> ni >> mi >> ki;
    vector> edges(mi);
    for (auto& e : edges) {
        cin >> e[0] >> e[1];
    }
    while (ki--) {
        cin >> ai;
        init();
        for (auto& e : edges) {
            if (e[0] != ai and e[1] != ai) {  //边的两端点都不是ai,可以进行合并
                unionSets(e[0], e[1]);
            }
        }
        gg num = 0;  //记录连通分量的数量
        for (gg i = 1; i <= ni; ++i) {  //计算不包括ai的集合个数
            if (i != ai and i == ufs[i]) {
                ++num;
            }
        }
        cout << num - 1 << "n";
    }
    return 0;
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/849307.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号