Leetcode-并查集/BFS/DFS-399. 除法求值
题目:
给你一个变量对数组 equations 和一个实数值数组 values 作为已知条件,其中 equations[i] = [Ai, Bi] 和 values[i] 共同表示等式 Ai / Bi = values[i] 。每个 Ai 或 Bi 是一个表示单个变量的字符串。
另有一些以数组 queries 表示的问题,其中 queries[j] = [Cj, Dj] 表示第 j 个问题,请你根据已知条件找出 Cj / Dj = ? 的结果作为答案。
返回 所有问题的答案 。如果存在某个无法确定的答案,则用 -1.0 替代这个答案。
注意:输入总是有效的。你可以假设除法运算中不会出现除数为 0 的情况,且不存在任何矛盾的结果。
示例 1:
输入:equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
输出:[6.00000,0.50000,-1.00000,1.00000,-1.00000]
解释:
条件:a / b = 2.0, b / c = 3.0
问题:a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
结果:[6.0, 0.5, -1.0, 1.0, -1.0 ]
示例 2:
输入:equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
输出:[3.75000,0.40000,5.00000,0.20000]
示例 3:
输入:equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
输出:[0.50000,2.00000,-1.00000,-1.00000]
提示:
1 <= equations.length <= 20
equations[i].length == 2
1 <= Ai.length, Bi.length <= 5
values.length == equations.length
0.0 < values[i] <= 20.0
1 <= queries.length <= 20
queries[i].length == 2
1 <= Cj.length, Dj.length <= 5
Ai, Bi, Cj, Dj 由小写英文字母与数字组成
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/evaluate-division
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
一开始只想到DFS做法,把并查集全忘了,此处记录一下官方带权值的并查集做法
代码:
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
int equationsSize = equations.size();
UnionFind unionFind = new UnionFind(2 * equationsSize);
// 第 1 步:预处理,将变量的值与 id 进行映射,使得并查集的底层使用数组实现,方便编码
Map<String, Integer> hashMap = new HashMap<>(2 * equationsSize);
int id = 0;
for (int i = 0; i < equationsSize; i++) {
List<String> equation = equations.get(i);
String var1 = equation.get(0);
String var2 = equation.get(1);
if (!hashMap.containsKey(var1)) {
hashMap.put(var1, id);
id++;
}
if (!hashMap.containsKey(var2)) {
hashMap.put(var2, id);
id++;
}
unionFind.union(hashMap.get(var1), hashMap.get(var2), values[i]);
}
// 第 2 步:做查询
int queriesSize = queries.size();
double[] res = new double[queriesSize];
for (int i = 0; i < queriesSize; i++) {
String var1 = queries.get(i).get(0);
String var2 = queries.get(i).get(1);
Integer id1 = hashMap.get(var1);
Integer id2 = hashMap.get(var2);
if (id1 == null || id2 == null) {
res[i] = -1.0d;
} else {
res[i] = unionFind.isConnected(id1, id2);
}
}
return res;
}
private class UnionFind {
private int[] parent;
/**
* 指向的父结点的权值
*/
private double[] weight;
public UnionFind(int n) {
this.parent = new int[n];
this.weight = new double[n];
for (int i = 0; i < n; i++) {
parent[i] = i;
weight[i] = 1.0d;
}
}
public void union(int x, int y, double value) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return;
}
parent[rootX] = rootY;
// 关系式的推导请见「参考代码」下方的示意图
weight[rootX] = weight[y] * value / weight[x];
}
/**
* 路径压缩
*
* @param x
* @return 根结点的 id
*/
public int find(int x) {
if (x != parent[x]) {
int origin = parent[x];
parent[x] = find(parent[x]);
weight[x] *= weight[origin];
}
return parent[x];
}
public double isConnected(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY) {
return weight[x] / weight[y];
} else {
return -1.0d;
}
}
}
}
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
int nvars = 0;
Map<String, Integer> variables = new HashMap<String, Integer>();
int n = equations.size();
for (int i = 0; i < n; i++) {
if (!variables.containsKey(equations.get(i).get(0))) {
variables.put(equations.get(i).get(0), nvars++);
}
if (!variables.containsKey(equations.get(i).get(1))) {
variables.put(equations.get(i).get(1), nvars++);
}
}
int[] f = new int[nvars];
double[] w = new double[nvars];
Arrays.fill(w, 1.0);
for (int i = 0; i < nvars; i++) {
f[i] = i;
}
for (int i = 0; i < n; i++) {
int va = variables.get(equations.get(i).get(0)), vb = variables.get(equations.get(i).get(1));
merge(f, w, va, vb, values[i]);
}
int queriesCount = queries.size();
double[] ret = new double[queriesCount];
for (int i = 0; i < queriesCount; i++) {
List<String> query = queries.get(i);
double result = -1.0;
if (variables.containsKey(query.get(0)) && variables.containsKey(query.get(1))) {
int ia = variables.get(query.get(0)), ib = variables.get(query.get(1));
int fa = findf(f, w, ia), fb = findf(f, w, ib);
if (fa == fb) {
result = w[ia] / w[ib];
}
}
ret[i] = result;
}
return ret;
}
public void merge(int[] f, double[] w, int x, int y, double val) {
int fx = findf(f, w, x);
int fy = findf(f, w, y);
f[fx] = fy;
w[fx] = val * w[y] / w[x];
}
public int findf(int[] f, double[] w, int x) {
if (f[x] != x) {
int father = findf(f, w, f[x]);
w[x] = w[x] * w[f[x]];
f[x] = father;
}
return f[x];
}
}
说明:代码 weight[rootX] = weight[y] * value / weight[x]; 的推导过程,主要需要明白各个变量的含义,由两条路径有向边的权值乘积相等得到相等关系,然后做等价变换即可。
复杂度分析:
时间复杂度:O((N + Q)\log A)
构建并查集 O(NlogA) ,这里 N 为输入方程 equations 的长度,每一次执行合并操作的时间复杂度是 O(\log A) 这里 A是 equations 里不同字符的个数;
查询并查集 O(QlogA),这里 Q 为查询数组 queries 的长度,每一次查询时执行「路径压缩」的时间复杂度是 O(\log A)
空间复杂度:O(A):创建字符与 id 的对应关系 hashMap 长度为 A,并查集底层使用的两个数组 parent 和 weight 存储每个变量的连通分量信息,parent 和 weight 的长度均为 A。
BFS解法:
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
int nvars = 0;
Map<String, Integer> variables = new HashMap<String, Integer>();
int n = equations.size();
for (int i = 0; i < n; i++) {
if (!variables.containsKey(equations.get(i).get(0))) {
variables.put(equations.get(i).get(0), nvars++);
}
if (!variables.containsKey(equations.get(i).get(1))) {
variables.put(equations.get(i).get(1), nvars++);
}
}
// 对于每个点,存储其直接连接到的所有点及对应的权值
List<Pair>[] edges = new List[nvars];
for (int i = 0; i < nvars; i++) {
edges[i] = new ArrayList<Pair>();
}
for (int i = 0; i < n; i++) {
int va = variables.get(equations.get(i).get(0)), vb = variables.get(equations.get(i).get(1));
edges[va].add(new Pair(vb, values[i]));
edges[vb].add(new Pair(va, 1.0 / values[i]));
}
int queriesCount = queries.size();
double[] ret = new double[queriesCount];
for (int i = 0; i < queriesCount; i++) {
List<String> query = queries.get(i);
double result = -1.0;
if (variables.containsKey(query.get(0)) && variables.containsKey(query.get(1))) {
int ia = variables.get(query.get(0)), ib = variables.get(query.get(1));
if (ia == ib) {
result = 1.0;
} else {
Queue<Integer> points = new LinkedList<Integer>();
points.offer(ia);
double[] ratios = new double[nvars];
Arrays.fill(ratios, -1.0);
ratios[ia] = 1.0;
while (!points.isEmpty() && ratios[ib] < 0) {
int x = points.poll();
for (Pair pair : edges[x]) {
int y = pair.index;
double val = pair.value;
if (ratios[y] < 0) {
ratios[y] = ratios[x] * val;
points.offer(y);
}
}
}
result = ratios[ib];
}
}
ret[i] = result;
}
return ret;
}
}
class Pair {
int index;
double value;
Pair(int index, double value) {
this.index = index;
this.value = value;
}
}
复杂度分析
时间复杂度:O(ML+Q\cdot(L+M)),其中 M为边的数量,Q 为询问的数量,L 为字符串的平均长度。构建图时,需要处理 M 条边,每条边都涉及到 O(L) 的字符串比较;处理查询时,每次查询首先要进行一次 O(L) 的比较,然后至多遍历 O(M) 条边。
空间复杂度:O(NL+M),其中 N 为点的数量,M 为边的数量,L 为字符串的平均长度。为了将每个字符串映射到整数,需要开辟空间为 O(NL) 的哈希表;随后,需要花费 O(M) 的空间存储每条边的权重;处理查询时,还需要 O(N)的空间维护访问队列。最终,总的复杂度为 O(NL+M+N) = O(NL+M)
DFS
自己写的,跟BFS思路差不多,深搜
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
HashMap<String, HashMap<String,Double>> map=new HashMap<String, HashMap<String,Double>>();
double[] res=new double[queries.size()];
int all=0;
for( int i = 0 ; i < equations.size() ; i++)
{
String a = equations.get(i).get(0);
String b = equations.get(i).get(1);
double v = values[i];
HashMap<String,Double> divisor1 = new HashMap<String,Double>();
divisor1.put(b,v);
HashMap<String,Double> divisor2 = new HashMap<String,Double>();
divisor2.put(a,1/v);
if(!map.containsKey(a))
{
map.put(a,divisor1);
all+=1;
}
HashMap<String,Double> av = map.get(a);
av.put(b,v);
map.put(a,av);
if(!map.containsKey(b))
{
map.put(b,divisor2);all+=1;
}
HashMap bv = map.get(b);
bv.put(a,1/v);
map.put(b,bv);
}
for( int i = 0 ; i < queries.size() ; i++)
{
String a = queries.get(i).get(0);
String b = queries.get(i).get(1);
if(map.containsKey(a)&&map.containsKey(b))
{
if(map.get(a).containsKey(b))
{
res[i]=map.get(a).get(b);
}
if(a.equals(b))
{
res[i]=1.0;
}
else
{
Stack<String> st = new Stack<String>();
st.push(a);
HashMap<String,Double> vis = new HashMap<String,Double>();
for(String key : map.keySet())
{
vis.put(key,-1.0);
}
vis.put(a,1.0);
while (!st.isEmpty() && vis.get(b) < 0) {
String x = st.pop();
for(String key : map.get(x).keySet())
{
String y = key;
double val = map.get(x).get(y);
if (vis.get(y) < 0)
{
vis.put(y,vis.get(x) * val);
st.push(y);
}
}
}
res[i]=vis.get(b);
}
}
else
{
res[i]=-1.0;
}
}
return res;
}
}
Floyd 算法
对于查询数量很多的情形,如果为每次查询都独立搜索一次,则效率会变低。为此,我们不妨对图先做一定的预处理,随后就可以在较短的时间内回答每个查询。
在本题中,我们可以使用Floyd 算法,预先计算出任意两点之间的距离
class Solution {
public double[] calcEquation(List<List<String>> equations, double[] values, List<List<String>> queries) {
int nvars = 0;
Map<String, Integer> variables = new HashMap<String, Integer>();
int n = equations.size();
for (int i = 0; i < n; i++) {
if (!variables.containsKey(equations.get(i).get(0))) {
variables.put(equations.get(i).get(0), nvars++);
}
if (!variables.containsKey(equations.get(i).get(1))) {
variables.put(equations.get(i).get(1), nvars++);
}
}
double[][] graph = new double[nvars][nvars];
for (int i = 0; i < nvars; i++) {
Arrays.fill(graph[i], -1.0);
}
for (int i = 0; i < n; i++) {
int va = variables.get(equations.get(i).get(0)), vb = variables.get(equations.get(i).get(1));
graph[va][vb] = values[i];
graph[vb][va] = 1.0 / values[i];
}
for (int k = 0; k < nvars; k++) {
for (int i = 0; i < nvars; i++) {
for (int j = 0; j < nvars; j++) {
if (graph[i][k] > 0 && graph[k][j] > 0) {
graph[i][j] = graph[i][k] * graph[k][j];
}
}
}
}
int queriesCount = queries.size();
double[] ret = new double[queriesCount];
for (int i = 0; i < queriesCount; i++) {
List<String> query = queries.get(i);
double result = -1.0;
if (variables.containsKey(query.get(0)) && variables.containsKey(query.get(1))) {
int ia = variables.get(query.get(0)), ib = variables.get(query.get(1));
if (graph[ia][ib] > 0) {
result = graph[ia][ib];
}
}
ret[i] = result;
}
return ret;
}
}
本文地址:https://blog.csdn.net/qq_40421671/article/details/112274394
上一篇: Aria2 RPC接口协议和Java的本地调用实现
下一篇: jdk9新特性学习