WEEK#9 Graph_Evaluate Division

Description of the Problem

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.


Thinking Process

Note that A / B = K and B / A = 1 / K, the problem can be transformed into a graph problem, where A / B = K means that there exists a path of length K from vertex A to B and a path of length 1/K from vertex B to A.
Furthermore, if 2 vertexes are indirectly connected, length of the path between them would be the product of lengths of all the paths connecting these 2 vertexes.
So the problem now is to construct a graph according to equations and values, moreover we need to use DFS to check if there's any path between 2 indirectly connected vertexes and calculate those path's length. Upon doing so, the rest would be to use queries to retrieve the values in RelationMatrix.


A general idea

Seeing that equations are composed of two strings and a double, the relation matrix of the graph is such data structure that it use a pair of strings as key, and map to a double as value.

class Graph {
private:
    vector<string> Vertexs;
    map<pair<string, string>, double> RelationMatrix;

public:
    Graph() {
        Vertexs.resize(0);
    }

    void AddEdge(string vertex1, string vertex2, double length) {
        RelationMatrix[make_pair(vertex1, vertex2)] = length;
        RelationMatrix[make_pair(vertex2, vertex1)] = 1 / length;
    }

    void AddConnectedEdge() {
        for (int i = 0; i < Vertexs.size(); i++) {
            for (int j = 0; j < Vertexs.size(); j++) {
                for (int k = 0; k < Vertexs.size(); k++) {
                    if (RelationMatrix.find(make_pair(Vertexs[i],Vertexs[k])) != RelationMatrix.end() &&
                        RelationMatrix.find(make_pair(Vertexs[k], Vertexs[j])) != RelationMatrix.end()) {
                        AddEdge(Vertexs[i], Vertexs[j], RelationMatrix.find(make_pair(Vertexs[i], Vertexs[k]))->second * RelationMatrix.find(make_pair(Vertexs[k], Vertexs[j]))->second);
                        AddEdge(Vertexs[j], Vertexs[i], 1 / (RelationMatrix.find(make_pair(Vertexs[i], Vertexs[k]))->second * RelationMatrix.find(make_pair(Vertexs[k], Vertexs[j]))->second));
                    }
                }
            }
        }
    }

    void SetVertexs(unordered_set<string> vertexs) {
        Vertexs.resize(vertexs.size());
        int count = 0;
        for (auto it = vertexs.begin(); it != vertexs.end(); it++)
            Vertexs[count++] = *it;
    }

    double GetLength(string vertex1, string vertex2) {
        map<pair<string, string>, double>::iterator it;
        it = RelationMatrix.find(make_pair(vertex1, vertex2));
        if (it != RelationMatrix.end())
            return it->second;
        return -1;
    }
};


class Solution {
public:
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        unordered_set<string> vertexs;
        Graph* graph = new Graph();
        for (int i = 0; i < equations.size(); i++) {
            graph->AddEdge(equations[i].first.substr(0, equations[i].first.size()-1), equations[i].second, values[i]); // construct relation matrix by equations.
            vertexs.insert(equations[i].first.substr(0, equations[i].first.size() - 1)); // adding vertexes by equations
            vertexs.insert(equations[i].second);
        }
        graph->SetVertexs(vertexs);
        graph->AddConnectedEdge(); // find indirectly connected vertexes and calculate the path's length between them
        vector<double> results;
        for (auto i : queries) { // use queries to retrieve values
            if (vertexs.find( i.first) != vertexs.end() && i.first == i.second)
                results.push_back(double(1));
            else
                results.push_back(graph->GetLength(i.first, i.second));
        }
        return results;
    }
};

This algorithm runs correct locally but fails all test cases in leetcodeOJ.

The incompleteness of this algorithm lies in the AddConnectEdge part. Yeah, it would work if there's invariably one vertex between 2 indirectly connected vertexes (i.e. A->B->C),
then length(A,C) = length(A,B) * length(B,C).
But what if there is more than one vertex in between?
(like A->D->B->C->E) ... well ... eh ... Awkwardly it works too....

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,830评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,992评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,875评论 0 331
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,837评论 1 271
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,734评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,091评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,550评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,217评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,368评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,298评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,350评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,027评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,623评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,706评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,940评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,349评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,936评论 2 341

推荐阅读更多精彩内容

  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,287评论 0 23
  • (一) 不善于拍照,不善于言辞,不善于推销,估计是工程师的通病。 ——今天在网上看到的一句话。 由此可见,我并不是...
    睿秋阅读 487评论 0 3
  • 肖小二啊阅读 112评论 0 0
  • 刚刚看了部电影《28岁未成年》,好像有很多话要说,可是好像很多话又只能在心里。十七岁的凉夏和二十八岁的凉夏,一个率...
    Kiwi刘阅读 255评论 0 0