[Leetcode 399]Evaluate Division

32 篇文章 0 订阅
15 篇文章 0 订阅

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 {
public:                //转化为图
    
    vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
        int len=equations.size();
        int len_q=queries.size();
        vector<double> res(len_q);
        for(int i=0;i<len;i++) {
            pair<string,string> tmp=equations[i];
            edge[tmp.first].push_back(tmp.second);
            edge_w[tmp]=values[i];
            if(values[i]!=0) {
                pair<string,string> tmp2;
                tmp2.first=tmp.second;tmp2.second=tmp.first;
                edge[tmp2.first].push_back(tmp2.second);
                edge_w[tmp2]=1.0/values[i];
            }
        }
        for(int i=0;i<len_q;i++) {
            pair<string,string> t=queries[i];
            string a,b;
            a=t.first,b=t.second;
            res[i]=-1.0;
            if(edge.find(a)!=edge.end()&&edge.find(b)!=edge.end()) {
                bool f=false;
                dfs(t.first,"",1.0,t.second,res[i],f);
            }
        }
        return res;
    }
    
    void dfs(string cur,string f,double dis,string e,double& t,bool& flag) {
        if(flag) return;
        if(cur==e) {
            t=dis;
            flag=true;
            return ;
        }
        for(int i=0;i<edge[cur].size();i++) {
            string nex=edge[cur][i];
            if(nex==f) continue;
            double w=edge_w[pair<string,string>(cur,nex)];
            dfs(nex,cur,dis*w,e,t,flag);
        }
    }
private:
    map<pair<string,string>,double> edge_w;
    map<string,vector<string>> edge;
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值