并查集问题

C++实现畅通工程求解

输入:第一行:城镇数目n,道路数目m
   接下的每一行表示:某条道路连接的城镇号

输出:至少还需要建设的道路数目,才能将所有的城镇连接起来

例子:

输入:
3 3
1 2
1 2
2 1
输出:
1

解释:要使城镇123连通,还需要修建23之间的连通路;即还需要修建一条路

//cpp实现问题求解
#include<iostream>
using namespace std;
const int N = 1005;
int towns[N];

//查
int find(int t){
    if (towns[t] == -1) return t;
    return towns[t] = find(towns[t]);
}

//并
void bing(int a, int b){
    int t1 = find(a);
    int t2 = find(b);
    if (t1 != t2) towns[t1] = t2;
}

//主函数
int main(){
    int n, m;
    while (cin >> n, n){
        cin >> m;
        memset(towns, -1, sizeof(towns));
        int ans = 0;
        for (int i = 0; i < m; i++){
   	       int a, b;
   	       cin >> a >> b;
   	       bing(a, b);
        }
  	   for (int i = 1; i <= n; i++)
        if (towns[i] == -1) ans++;
  	   cout << ans - 1 << endl;
    }
    return 0;
}

等式方程的可满足性(LeetCode990)

输入:["a==b","b!=a"]
输出:false
解释:如果我们指定,a = 1 且 b = 1,那么可以满足第一个方程,但无法满足第二个方程。没有办法分配变量同时满足这两个方程。

输出:["b==a","a==b"]
输入:true
解释:我们可以指定 a = 1 且 b = 1 以满足满足这两个方程。

输入:["a==b","b!=c","c==a"]
输出:false
class UnionFind {
private:
    vector<int> parent;

public:
    UnionFind(){
        parent.resize(26);
        iota(parent.begin(), parent.end(), 0);
    }

    int find(int index) {
        if (index == parent[index]) {
            return index;
        }
        parent[index] = find(parent[index]);
        return parent[index];
    }

    void unite(int index1, int index2) {
        parent[find(index1)] = find(index2); 
    }
};


class Solution {
public:
    bool equationsPossible(vector<string>& equations) {
        // 利用并查集求解
        UnionFind uf;
        for (const string& str : equations) {
            if (str[1] == '=') {
                int index1 = str[0] - 'a';
                int index2 = str[3] - 'a';
                uf.unite(index1, index2);
            }
        }
        for (const string& str : equations) {
            if (str[1] == '!') {
                int index1 = str[0] - 'a';
                int index2 = str[3] - 'a';
                if (uf.find(index1) == uf.find(index2)) {
                    return false;
                }
            }
        }
        return true;
    }
};

参考:
https://blog.csdn.net/qq_33677789/article/details/51296929

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值