399. Evaluate Division 难度:medium 类别:图

本文介绍了一种使用图算法解决变量方程问题的方法。通过将方程转化为图的节点与边,利用宽度优先搜索算法寻找两个变量之间的路径及权值乘积,从而求解特定的数学查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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 ].


思路:

这题可以转化为图的两点之间是否存在路径的问题,当题目给出累死a / b = 2.0的等式时,可以转化为节点a到节点b有一条边,权值为2.0,要求a / c时即意味着要求a和c之间是否有路径,并且结果为路径权值的乘积,本题用邻接表存储图的结构,用宽度优先搜索搜索两点之间是否有路径。


程序:

double bfs(vector<vector< pair<int,double> > > &adj,int a,int b)
{
	vector<bool> visited(adj.size(),false);
	vector<double> ans(adj.size(),1.0);
	queue<int> q;
	
	q.push(a);
	visited[a] = true;
	
	while(!q.empty())
	{
		int u = q.front();
		q.pop();
		
		for(int i = 0;i < adj[u].size();i++)
		{
			int x = adj[u][i].first;
			double y = adj[u][i].second;
			
			if(visited[x])
				continue;
			
			ans[x] = ans[u] * y;
			if(x == b)
				return ans[x];
			
			q.push(x);
			visited[x] = true;
		}
	}
	
	return -1.0;
}
<span style="font-family: Arial, Helvetica, sans-serif;">
</span>

vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) 
<span style="font-family: Arial, Helvetica, sans-serif;">{</span>
 	map<string,int> m;
	vector< vector< pair<int,double> > > adj;
	
	for(int i = 0;i < equations.size();i++)
	{
		string x = equations[i].first;
		string y = equations[i].second;
		
		if(!m.count(x))
		{
			m[x] = adj.size();
			vector< pair<int,double> > t;
			adj.push_back(t);
		}
		
		if(!m.count(y))
		{
			m[y] = adj.size();
			vector< pair<int,double> > t;
			adj.push_back(t);
		}
		
		int a = m[x];
		int b = m[y];
		
		adj[a].push_back({b,values[i]});
		adj[b].push_back({a,1 / values[i]});
	}
	
	vector<double> res;
    
	for(int i = 0;i < queries.size();i++)
	{
		string x = queries[i].first;
		string y = queries[i].second;
		
		if(!m.count(x)||!m.count(y))
			res.push_back(-1.0);
		
		else
		{
			if(x == y)
				res.push_back(1.0);
			
			else
			{
				int a = m[x];
				int b = m[y];
				
				double ans = bfs(adj,a,b);
				res.push_back(ans);
			}
		}
	}
	
	return res;  
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值