题目:
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;
}