UnionFind就是acm中常用的并查集...

并查集常用操作

另外补充一下STL常用操作

相关问题:

547. Friend Circles

纯裸题噢...

 class Solution {
public:
int root[];
bool v[]; void uf_init(int x)
{
for(int i=;i<=x;i++)
root[i]=i;
} int uf_find(int x)
{
if(x!=root[x])
root[x]=uf_find(root[x]);
return root[x];
} void uf_union(int x, int y)
{
int tx=uf_find(x);
int ty=uf_find(y);
if(tx!=ty)
root[tx]=ty;
} int findCircleNum(vector<vector<int>>& M)
{
int kn=M.size();
uf_init(kn);
for(int i=;i<kn;i++)
for(int j=i+;j<kn;j++)
if(M[i][j])
uf_union(i,j); memset(v,,sizeof(v));
int cnt=;
for(int i=;i<kn;i++)
if(!v[uf_find(i)])
{
cnt++;
v[uf_find(i)]=true;
}
return cnt;
}
};

Graph Valid Tree

(权限题做不了嘤嘤嘤)

684. Redundant Connection

并查集找无向图中的环,比较裸的题

 #include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cstring>
#include <cstdio>
using namespace std; class Solution {
public:
int root[]; void uf_init(int x)
{
for(int i=;i<=x;i++)
root[i]=i;
} int uf_find(int x)
{
if(x!=root[x])
root[x]=uf_find(root[x]);
return root[x];
} void uf_union(int x, int y)
{
int tx=uf_find(x);
int ty=uf_find(y);
if(tx!=ty)
root[tx]=ty;
} vector<int> findRedundantConnection(vector<vector<int>>& edges)
{
int k=edges.size();
int kx,ky;
uf_init(k);
for(int i=;i<k;i++)
{
kx=edges[i][];
ky=edges[i][];
if(uf_find(kx)!=uf_find(ky))
uf_union(kx,ky);
else
return(edges[i]);
}
}
}; int main()
{
Solution sl;
return ;
}

685. Redundant Connection II = 改成了有向图,复杂了许多......

不会做嘤嘤嘤

721. Accounts Merge

比较裸的并查集。将email重复的两个账户union一下,最后再输出每个集合

 class Solution:
def uf_init(self,x):
self.root=[0 for i in range(x+10)]
for i in range(x):
self.root[i]=i def uf_find(self, x):
if(x!=self.root[x]):
self.root[x]=self.uf_find(self.root[x])
return self.root[x] def uf_union(self, x, y):
tx=self.uf_find(x)
ty=self.uf_find(y)
if(tx!=ty):
self.root[tx]=ty def similar(self, acc1, acc2):
res=0
if(acc1[0]!=acc2[0]):
return res
for i in acc1[1:]:
for j in acc2[1:]:
if(i==j):
res=1
return res def accountsMerge(self, accounts):
"""
:type accounts: List[List[str]]
:rtype: List[List[str]]
"""
ka=len(accounts)
print(ka)
self.uf_init(ka) hsh={}
for i in range(ka):
for j in range(len(accounts[i])-1):
if(hsh.get(accounts[i][j+1])!=None):
dx=hsh[accounts[i][j+1]]
uf_union(dx,i)
else:
hsh[accounts[i][j+1]]=i dct=[set() for i in range(ka)]
lbl=["" for i in range(ka)]
for i in range(ka):
ui=self.uf_find(i)
lbl[ui]=accounts[i][0]
for j in range(len(accounts[i])-1):
dct[ui].add(accounts[i][j+1]) ans=[]
for i in range(ka):
if(lbl[i]!=""):
tmp=[]
for j in dct[i]:
tmp.append(j)
tmp.sort()
tmp=[lbl[i]]+tmp
ans.append(tmp) return ans

注意用hashmap优化掉两重循环的方法,比较常用

         for i in range(0,ka):
for j in range(i+1,ka):
if(self.similar(accounts[i],accounts[j])):
self.uf_union(i,j)

优化前

         hsh={}
for i in range(ka):
for j in range(len(accounts[i])-1):
if(hsh.get(accounts[i][j+1])!=None):
dx=hsh[accounts[i][j+1]]
uf_union(dx,i)
else:
hsh[accounts[i][j+1]]=i

优化后

399. Evaluate Division

一开始想了半天是不是数学题...其实在纸上画画可以发现,这是一个图论题......

这样就转化成了求图中每对节点最短路问题,这时小学生会选择用Floyd算法,时间复杂度O(N^3)

 #define GMAX 0x7f7f7f7f
// initiate double with maxium value:
// https://blog.csdn.net/popoqqq/article/details/38926889 class Solution {
public:
double graph[][]; vector<double> calcEquation(vector<pair<string, string>> equations,
vector<double>& values,
vector<pair<string, string>> queries)
{
memset(graph,0x7f,sizeof(graph));
cout<<graph[][]<<endl;
int kl=values.size(), kq=queries.size();
map<string,int> dict;
int dcnt=,dx,dy;
for(int i=;i<kl;i++)
{
if(dict.find(equations[i].first)==dict.end())
{
dcnt++;
dict.insert(pair<string, int>(equations[i].first, dcnt));
}
if(dict.find(equations[i].second)==dict.end())
{
dcnt++;
dict.insert(pair<string, int>(equations[i].second, dcnt));
}
dx=dict[equations[i].first];
dy=dict[equations[i].second];
graph[dx][dy]=values[i];
graph[dy][dx]=/values[i];
cout<<dx<<"--"<<dy<<" "<<values[i]<<endl;
} for(int i=;i<=dcnt;i++)
graph[i][i]=;
for(int k=;k<=dcnt;k++)
for(int i=;i<=dcnt;i++)
for(int j=;j<=dcnt;j++)
if(graph[i][k]<GMAX && graph[k][j]<GMAX)
graph[i][j]=min(graph[i][j],graph[i][k]*graph[k][j]); vector<double> ans;
string sx,sy;
for(int i=;i<kq;i++)
{
sx=queries[i].first;
sy=queries[i].second;
if(dict.find(sx)==dict.end() || dict.find(sy)==dict.end())
ans.push_back(-1.0);
else
{
dx=dict[sx];
dy=dict[sy];
if(graph[dx][dy]<GMAX)
ans.push_back(graph[dx][dy]);
else
ans.push_back(-1.0);
cout<<dx<<"__"<<dy<<endl;
}
} return ans;
}
};

但大学生们会用并查集来解呢

balabala

UnionFind问题总结的更多相关文章

  1. Union-Find 检测无向图有无环路算法

    不相交集合数据结构(Disjoint-set data structure)是一种用于跟踪集合被分割成多个不相交的子集合的数据结构,每个集合通过一个代表来标识,代表即集合中的某个成员. Union-F ...

  2. UVA - 11987 Almost Union-Find[并查集 删除]

    UVA - 11987 Almost Union-Find I hope you know the beautiful Union-Find structure. In this problem, y ...

  3. 并查集(union-find)算法

    动态连通性 . 假设程序读入一个整数对p q,如果所有已知的所有整数对都不能说明p和q是相连的,那么将这一整数对写到输出中,如果已知的数据可以说明p和q是相连的,那么程序忽略p q继续读入下一整数对. ...

  4. UVa 11987 Almost Union-Find(支持删除操作的并查集)

    传送门 Description I hope you know the beautiful Union-Find structure. In this problem, you’re to imple ...

  5. 有一种算法叫做“Union-Find”?

    前言: 不少搞IT的朋友听到“算法”时总是觉得它太难,太高大上了.今天,跟大伙儿分享一个比较俗气,但是却非常高效实用的算法,如标题所示Union-Find,是研究关于动态连通性的问题.不保证我能清晰的 ...

  6. Union-Find Algorithm

    Union-Find Algrithm is used to check whether two components are connected or not. Examples: By using ...

  7. 并查集 Union-Find

    并查集能做什么? 1.连接两个对象; 2.查询两个对象是否在一个集合中,或者说两个对象是否是连接在一起的. 并查集有什么应用? 1. Percolation问题. 2. 无向图连通子图个数 3. 最近 ...

  8. 最小生成树--Prim算法,基于优先队列的Prim算法,Kruskal算法,Boruvka算法,“等价类”UnionFind

    最小支撑树树--Prim算法,基于优先队列的Prim算法,Kruskal算法,Boruvka算法,“等价类”UnionFind 最小支撑树树 前几节中介绍的算法都是针对无权图的,本节将介绍带权图的最小 ...

  9. UVA 11987 - Almost Union-Find(并查集)

    UVA 11987 - Almost Union-Find 题目链接 题意:给定一些集合,操作1是合并集合,操作2是把集合中一个元素移动到还有一个集合,操作3输出集合的个数和总和 思路:并查集,关键在 ...

  10. 并查集(Union-Find)算法介绍

    原文链接:http://blog.csdn.net/dm_vincent/article/details/7655764 本文主要介绍解决动态连通性一类问题的一种算法,使用到了一种叫做并查集的数据结构 ...

随机推荐

  1. AlexNet实践

    注释: CNN使用TF搭建比较简单,就像Hough检测使用CV很简单一样.但是怎么使用CNN去做一些实际操作,或者说怎么使用现有的方法进行慢慢改进,这是一个很大的问题! 直接跟着书本或者视频学习有点膨 ...

  2. Unable to complete the scan for annotations for web application [/wrs] due to a StackOverflowError. Possible root causes include a too low setting for -Xss and illegal cyclic inheritance dependencies.

    tomcat启动报错:Jul 20, 2018 11:48:37 AM org.apache.catalina.core.ContainerBase addChildInternalSEVERE: C ...

  3. python:选房抽签小工具

    1.房间号和姓名写在house_name.xls的house标签页中[注意!名字均不要改动]2.运行house.py3.当前同目录下会生成result.xls,即为结果:程序运行过程中不要打开该文件, ...

  4. python 列表复制给另一个列表,改值两个列表均会改变(备忘)

    http://blog.csdn.net/lc_lc2000/article/details/53135839 本意是使A = B,B为一个列表,结果在后续对A的操作中,导致B中的值也改变了,才回忆起 ...

  5. leetcode15

    class Solution { public List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); Li ...

  6. IDEA使用SpringBoot 、maven创建微服务的简单过程

    使用IDEA新建一个简单的微服务 1. 打开IDEA,File -> New  -> project 打开如下图1-1所示的对话框 图 1-1 2.点击"Next"按钮 ...

  7. PhoenixFD插件流体模拟——UI布局【Simulation】详解

    前言 之前使用RealFlow做流体模拟,但是总得和3ds导来导去,略显麻烦,特意学习PhoenixFD插件,直接在3ds中进行流体模拟.若读者有更好的流体模拟方法,欢迎在评论区交流. 原文地址:ht ...

  8. poj 2349 求最小生成树里面第m长的边

    题目链接:https://vjudge.net/problem/POJ-2349 题意: 题目就是要我们找到一个最小的值D,把图里面所有大于D的边去掉之后剩余的连通分支的数量为S.这个就是找这个图里面 ...

  9. laravel简书(1)

    Laravel的社区生态 中文社区(http://laravel-china.org) 5.4中文文档(http://d.laravel-china.org/docs/5.4) Laravel源码地址 ...

  10. springboot中使用ContextLoaderListener.getCurrentWebApplicationContext();获取WebApplicationContext为空问题

    WebApplicationContext applicationContext = ContextLoaderListener.getCurrentWebApplicationContext(); ...