Evaluate Division

題目
Equations are given in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating point number). Given some queries, return the answers. If the answer does not exist, return -1.0.

Example:
Given a / b = 2.0, b / c = 3.0.
queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ? .
return [6.0, 0.5, -1.0, 1.0, -1.0 ].

The input is: vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries , where equations.size() == values.size(), and the values are positive. This represents the equations. Return vector<double>.

According to the example above:

equations = [ ["a", "b"], ["b", "c"] ],
values = [2.0, 3.0],
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ].
The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.

答案

class Solution {

    /*
        思路

        Model each letter as a node, the relationship between two letters as an edge
        Given the example above, we have the following graph:
        a---2-->b
        b---1/2-->a
        b---3-->c
        c---1/3-->b
    */

    class GEdge {
        double weight;
        String dest;

        public GEdge(double weight, String dest) {
            this.weight = weight;
            this.dest = dest;
        }
    }

    public double[] calcEquation(String[][] equations, double[] values, String[][] queries) {
        Map<String,List<GEdge>> g = new HashMap<>();

        // Build graph here
        for(int i = 0; i < equations.length; i++) {
            String numerator = equations[i][0];
            String denominator = equations[i][1];

            // Add this edge to node numerator
            List<GEdge> edges = g.get(numerator);
            if(edges == null) {
                edges = new ArrayList<GEdge>();
                g.put(numerator, edges);
            }
            edges.add(new GEdge(values[i], denominator));

            // Add this edge to node denominator
            edges = g.get(denominator);
            if(edges == null) {
                edges = new ArrayList<GEdge>();
                g.put(denominator, edges);
            }
            edges.add(new GEdge(1 / values[i], numerator));
        }
        // Dfs search here
        double[] ans = new double[queries.length];
        Set<String> visited = new HashSet<>();
        for(int i = 0; i < queries.length; i++) {
            if(!g.containsKey(queries[i][0]) || !g.containsKey(queries[i][1]))
                ans[i] = -1.0;
            else
                ans[i] = dfs(g, visited, queries[i][0], queries[i][1], 1.0);
        }
        return ans;
    }

    /*
        Start from numerator, search for denominator
        If not found return -1.0
        Otherwise return the edge weight from parent node to current node

    */
    public double dfs(Map<String,List<GEdge>> g, Set<String> visited, String curr, String denominator, double edge_weight) {
        if(curr.equals(denominator)) {
            return edge_weight;
        }

        double ret = -1.0;
        visited.add(curr);
        List<GEdge> edges = g.get(curr);
        for(GEdge e : edges) {
            if(!visited.contains(e.dest)) {
                ret = dfs(g, visited, e.dest, denominator, e.weight);
                if(ret != -1.0) break;
            }
        }
        visited.remove(curr);
        if(ret == -1.0) return ret;
        return ret * edge_weight;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子刻诊,更是在濱河造成了極大的恐慌,老刑警劉巖髓窜,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件震桶,死亡現(xiàn)場離奇詭異竣况,居然都是意外死亡鹊杖,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門绿映,熙熙樓的掌柜王于貴愁眉苦臉地迎上來擒滑,“玉大人,你說我怎么就攤上這事叉弦∝ひ唬” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵淹冰,是天一觀的道長钝诚。 經(jīng)常有香客問我,道長榄棵,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任潘拱,我火速辦了婚禮疹鳄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘芦岂。我一直安慰自己瘪弓,他們只是感情好,可當我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布禽最。 她就那樣靜靜地躺著腺怯,像睡著了一般。 火紅的嫁衣襯著肌膚如雪川无。 梳的紋絲不亂的頭發(fā)上呛占,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天,我揣著相機與錄音懦趋,去河邊找鬼晾虑。 笑死,一個胖子當著我的面吹牛仅叫,可吹牛的內(nèi)容都是我干的帜篇。 我是一名探鬼主播,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼诫咱,長吁一口氣:“原來是場噩夢啊……” “哼笙隙!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起坎缭,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤竟痰,失蹤者是張志新(化名)和其女友劉穎签钩,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凯亮,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡边臼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了假消。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片柠并。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖富拗,靈堂內(nèi)的尸體忽然破棺而出臼予,到底是詐尸還是另有隱情,我是刑警寧澤啃沪,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布粘拾,位于F島的核電站,受9級特大地震影響创千,放射性物質(zhì)發(fā)生泄漏缰雇。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一追驴、第九天 我趴在偏房一處隱蔽的房頂上張望械哟。 院中可真熱鬧,春花似錦殿雪、人聲如沸暇咆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽谬以。三九已至分苇,卻和暖如春草则,著一層夾襖步出監(jiān)牢的瞬間套么,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工索抓, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留薄霜,地道東北人。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓纸兔,卻偏偏與公主長得像惰瓜,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子汉矿,可洞房花燭夜當晚...
    茶點故事閱讀 45,685評論 2 360

推薦閱讀更多精彩內(nèi)容