题目描述
现有一些格式为A / B = k的等式,A和B均为字符串变量,k为一个实数(浮点数)。如果能够找到答案,则返回答案。若答案不存在,则返回-1.0。
样例
给出等式a / b = 2.0, b / c = 3.0。
问题为a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?。
返回[6.0, 0.5, -1.0, 1.0, -1.0 ]。
代码如下:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <utility>
#include <queue>
using namespace std;
#define maxn 128
struct Node
{
double v;
int index;
Node(int _index, double _v) :v(_v), index(_index){};
};
queue<Node> q;
map<string, int> mp;
pair<string, string> a[] = { make_pair("a", "b"), make_pair("b", "c"), make_pair("d", "c") };
double g[maxn][maxn];
vector<Node> eg[maxn];
double values[] = { 2.0, 3.0 ,2.0};//得数
pair<string, string> queries[] = { make_pair("a", "b"), make_pair("c", "a") };
double FindSolve(pair<string, string> p)
{
int s = mp[p.first];
int t = mp[p.second];
q.push(Node(s,1));
while (!q.empty())
{
Node cur = q.front(); q.pop();
if (cur.index == t){
return cur.v;
}
for (int i = 0; i < eg[cur.index].size(); i++)
{
int index = eg[cur.index][i].index;
double v = eg[cur.index][i].v;
q.push(Node(index,cur.v*v));
}
}
return -1.0;
}
int main()
{
int cnt = 1;//给字符串编号
for (int i = 0; i < 3; i++)
{
if (mp[a[i].first] == NULL){
mp[a[i].first] = cnt++;
}
if (mp[a[i].second] == NULL){
mp[a[i].second] = cnt++;
}
eg[mp[a[i].first]].push_back(Node(mp[a[i].second],values[i]));
eg[mp[a[i].second]].push_back(Node(mp[a[i].first], 1.0/values[i]));
//g[mp[a[i].first]][mp[a[i].second]] = values[i];
}
for (int i = 0; i < 2; i++){
printf("%lf\n", FindSolve(queries[i]));
}
return 0;
}