【并查集】Is it a tree?

本文深入探讨了并查集的基本概念及其在判断树形结构有效性中的应用,通过实例展示了如何通过并查集来判断一组节点连接是否形成合法的树形结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

A tree is a well-known data structure that is either empty (null, void, nothing) or is a set of
one or more nodes connected by directed edges between nodes satisfying the following properties.

There is exactly one node, called the root, to which no directed edges point.
Every node except the root has exactly one edge pointing to it.
There is a unique sequence of directed edges from the root to each node.
For example, consider the illustrations below, in which nodes are represented by circles and edges
are represented by lines with arrowheads. The first two of these are trees, but the last is not. 


In this problem you will be given several descriptions of collections of nodes connected by directed edges. For each of these you are to determine if the collection satisfies the definition of a tree or not.

Input
The input will consist of a sequence of descriptions (test cases) followed by a pair of negative integers. Each test case will consist of a sequence of edge descriptions followed by a pair of zeroes Each edge description will consist of a pair of integers; the first integer identifies the node from which the edge begins, and the second integer identifies the node to which the edge is directed. Node numbers will always be greater than zero.

Output
For each test case display the line "Case k is a tree." or the line "Case k is not a tree.", where k corresponds to the test case number (they are sequentially numbered starting with 1).

Sample Input

6 8  5 3  5 2  6 4
5 6  0 0

8 1  7 3  6 2  8 9  7 5
7 4  7 8  7 6  0 0

3 8  6 8  6 4
5 3  5 6  5 2  0 0
-1 -1

Sample Output

Case 1 is a tree.
Case 2 is a tree.
Case 3 is not a tree.
很裸的并查集,注意森林不是树。
Accode:

#include <cstdio>
#include <string>
#include <set>

const int maxN = 1010;
std::set <int> S; int F[maxN];
std::set <int>::iterator iter;

inline int getint()
{
    int res = 0; char tmp; bool sgn = 1;
    do tmp = getchar();
    while (!isdigit(tmp) && tmp - '-');
    if (tmp == '-') {sgn = 0; tmp = getchar();}
    do res = (res << 3) + (res << 1) + tmp - '0';
    while (isdigit(tmp = getchar()));
    return sgn ? res : -res;
}

int Find(int x)
{return F[x] == x ? x : F[x] = Find(F[x]);}

int main()
{
    freopen("tree.in", "r", stdin);
    freopen("tree.out", "w", stdout);
    for (int T = 1; ; ++T)
    {
        for (int i = 1; i < maxN; ++i) F[i] = i;
        S.clear(); int x, y; bool flag = 1;
        while ((x = getint(), y = getint()) > 0)
        {
            if (S.find(x) == S.end()) S.insert(x);
            if (S.find(y) == S.end()) S.insert(y);
            if (Find(x) == Find(y)) flag = 0;
            else F[F[y]] = F[x];
        }
        if (x < 0 || y < 0) break;
        if (flag)
        {
            iter = S.begin();
            for (; iter != S.end(); ++iter)
            if (Find(*iter) - Find(*(S.begin())))
            {flag = 0; break;}
        } //要注意空树,这里很容易出错。
        printf("Case %d is%s a tree.\n",
               T, flag ? "" : " not");
    }
    return 0;
}

Problem Statement Given is a weighted undirected connected graph G with N vertices and M edges, which may contain self-loops and multi-edges. The vertices are labeled as Vertex 1, Vertex 2, …, Vertex N. The edges are labeled as Edge 1, Edge 2, …, Edge M. Edge i connects Vertex a i ​ and Vertex b i ​ and has a weight of c i ​ . Here, for every pair of integers (i,j) such that 1≤i<j≤M, c i ​  =c j ​ holds. Process the Q queries explained below. The i-th query gives a triple of integers (u i ​ ,v i ​ ,w i ​ ). Here, for every integer j such that 1≤j≤M, w i ​  =c j ​ holds. Let e i ​ be an undirected edge that connects Vertex u i ​ and Vertex v i ​ and has a weight of w i ​ . Consider the graph G i ​ obtained by adding e i ​ to G. It can be proved that the minimum spanning tree T i ​ of G i ​ is uniquely determined. Does T i ​ contain e i ​ ? Print the answer as Yes or No. Note that the queries do not change T. In other words, even though Query i considers the graph obtained by adding e i ​ to G, the G in other queries does not have e i ​ . What is minimum spanning tree? The spanning tree of G is a tree with all of the vertices in G and some of the edges in G. The minimum spanning tree of G is the tree with the minimum total weight of edges among the spanning trees of G. Constraints 2≤N≤2×10 5 N−1≤M≤2×10 5 1≤a i ​ ≤N (1≤i≤M) 1≤b i ​ ≤N (1≤i≤M) 1≤c i ​ ≤10 9 (1≤i≤M) c i ​  =c j ​ (1≤i<j≤M) The graph G is connected. 1≤Q≤2×10 5 1≤u i ​ ≤N (1≤i≤Q) 1≤v i ​ ≤N (1≤i≤Q) 1≤w i ​ ≤10 9 (1≤i≤Q) w i ​  =c j ​ (1≤i≤Q,1≤j≤M) All values in input are integers.c++code
最新发布
03-23
这个问题是一个经典的最小生成树(Minimum Spanning Tree, MST)相关的算法问题,涉及加边查询并判断新加入的边是否会被包含在更新后的最小生成树中。 以下是解决该问题的具体思路及代码: --- ### **解题思路** 1. **理解输入**: - 图 `G` 已经给出,并且图可能是带权重、无向、连通的。 - 查询操作会添加一条新的边到原图上,并询问这条新增的边是否会出现在当前图的新最小生成树中。 2. **核心思想**: 最小生成树的核心性质之一是“贪心选择”。对于任意两点之间的路径,如果新加入的一条边权值比现有的最大路径权值更小,则它将替换掉原来的最大边成为新的最优路径的一部分。 3. **离线处理技巧**: 因为每个查询只会影响一次结果而不会改变整体结构,可以采用一种称为 *Kruskal 算法* 的经典方法构建初始图的 MST 并结合按需调整来高效地完成所有查询任务。 4. **关键步骤**: - 首先对原始图的所有边按照其权值排序; - 使用 Kruskal 构造出最初的 MST 树; - 对于每次插入的临时虚拟边 (即题目中的 e_i),我们只需比较它们相对于现有连接的关系即可得出答案。 --- ```cpp #include <bits/stdc++.h> using namespace std; struct UnionFind { vector<int> parent; vector<int> rank_; UnionFind(int n){ parent.resize(n+1); rank_.resize(n+1, 0); for(int i=0;i<=n;i++) parent[i] = i; } int find_set(int x){ return (parent[x]!=x)?parent[x]=find_set(parent[x]):x; } void union_set(int x,int y){ int fx=find_set(x), fy=find_set(y); if(fx==fy)return ; if(rank_[fx]>rank_[fy]){ parent[fy]=fx; }else{ parent[fx]=fy; if(rank_[fx]==rank_[fy])rank_[fy]++; } } }; int main(){ ios::sync_with_stdio(false); cin.tie(0); // Input N,M long long N,M;cin>>N>>M; struct Edge{long long u,v,w;}; vector<Edge> edges(M); for(long long i=0;i<M;i++) cin >> edges[i].u >> edges[i].v >> edges[i].w; sort(edges.begin(),edges.end(),[](const auto &a,const auto &b){return a.w<b.w;}); // Build initial MST using Kruscal's algorithm UnionFind uf(N); vector<long long> mstW; for(auto &[u,v,w]:edges){ if(uf.find_set(u)!=uf.find_set(v)){ uf.union_set(u,v); mstW.push_back(w); } } // Process Q Queries offline long long Q; cin >> Q; struct Query {long long id,u,v,w;}; vector<Query> queries(Q); for(long long qid=0;qid<Q;++qid){ cin >> queries[qid].u >> queries[qid].v >>queries[qid].w; queries[qid].id=qid; } // Sort both sets together based on weight w sort(queries.begin(),queries.end(),[](auto &l,auto &r)->bool{return l.w<r.w;}); string ans_str(Q,'?'); UnionFind uf_query(N); size_t ptr_edge=0; for(auto &q:queries){ while(ptr_edge<mstW.size() && mstW[ptr_edge]<q.w){ long long u_=edges[ptr_edge].u, v_=edges[ptr_edge].v; uf_query.union_set(u_,v_); ++ptr_edge; } bool res=(uf_query.find_set(q.u)!=uf_query.find_set(q.v)); ans_str[q.id]=(res?'Y':'N'); } cout << "\n"; for(char c:ans_str)cout<<(c=='Y'?"Yes\n":"No\n"); } ``` --- #### § 相关说明 上述代码基于 C++ 实现了针对此问题的有效解决方案。其中采用了并查集数据结构辅助快速合并节点以及检查联通状态的功能;同时利用排序特性简化了复杂度分析过程。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值