日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

并查集 - 除法求值

發布時間:2024/4/18 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 并查集 - 除法求值 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

題目鏈接

將所有等式關系轉化為同一變量的倍數。

class Solution { public:vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {int n = equations.size(), q = queries.size();vector<double> ret, fa(n*2), weight(n*2, 1.0);for (int i = 0; i < n*2; ++i) {fa[i] = i;}map<string, int> num;int now = 0;for (int i = 0; i < n; ++i) {if (num.find(equations[i][0]) == num.end()) {num[equations[i][0]] = now++;}if (num.find(equations[i][1]) == num.end()) {num[equations[i][1]] = now++;}int x = num[equations[i][0]];int y = num[equations[i][1]];int fx = find(fa, weight, x);int fy = find(fa, weight, y);fa[fx] = fy;weight[fx] = weight[y] / weight[x] * values[i];}for (int i = 0; i < q; ++i) {if (num.find(queries[i][0]) == num.end() || num.find(queries[i][1]) == num.end()) {ret.push_back(-1);continue;}int x = num[queries[i][0]];int y = num[queries[i][1]];int fx = find(fa, weight, x);int fy = find(fa, weight, y);if (fx != fy) {ret.push_back(-1);}else {ret.push_back(weight[x] / weight[y]);}}return ret;}int find(vector<double> &fa, vector<double> &weight, int x) {if (fa[x] != x) {int rt = find(fa, weight, fa[x]);weight[x] *= weight[fa[x]];fa[x] = rt;}return fa[x];} };

總結

以上是生活随笔為你收集整理的并查集 - 除法求值的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。