LeetCode 399. 除法求值
class Solution {
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries) {
unordered_set<string> node;//记录所有节点
unordered_map<string,unordered_map<string,double>> g;//存储图
int n=equations.size(),m=queries.size();
for(int i=0;i<n;i++)
{
string a=equations[i][0],b=equations[i][1];
double c=values[i];
//a->b的权值为c
node.insert(a);node.insert(b);
g[a][b]=c;g[b][a]=1/c;
}
vector<double> res;
for(int i=0;i<m;i++)//处理询问
{
string a=queries[i][0],b=queries[i][1];
if(node.find(a)==node.end()||node.find(b)==node.end())
res.push_back(-1);
else
{
double path=1;
unordered_map<string,bool> st;
st[a]=true;
if(!dfs(a,b,g,path,st)) path=-1;
res.push_back(path);
}
}
return res;
}
bool dfs(string a,string b,unordered_map<string,unordered_map<string,double>> &g,double &sum,unordered_map<string,bool> &st)
{
if(a==b)
return true;
for(auto item:g[a])
{
string t=item.first;
if(!st[t])
{
st[t]=true;
if(dfs(t,b,g,sum,st))
{
sum*=item.second;
return true;
}
}
}
return false;
}
};
有帮助的话可以点个赞,我会很开心的~
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?