问题描述:
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 ]
如果出现未知的字符或者是没有任何逻辑运算的字符之间的话,则返回-1.0,否则根据逻辑运算计算出结果。
问题分析:
数学的逻辑不可以轻易的通过各种复杂的逻辑判断写出来,那么转化成图的思想,将在逻辑判断中出现的字母都用图形中的一个node表示,任何出现的逻辑表达式可以看成图形中的关系,
逻辑计算a/c可以看成是从a出发的深度遍历搜索a到b=1.0*2.0=2.0,然后从b到c则为2.0*3.0=6.0
若出现其他节点或者是逻辑判断,也就是说图深度遍历到达不到的点的话则为-1.0.
code:
#include<algorithm>
#include<iostream>
#include<vector>
#include<set>
using namespace std;
#define MAXVALUE 32767
#define MAX 26
double edges[MAX][MAX];
bool visited[MAX];
double final[MAX];
class Solution {
public:
Solution(){}
vector<int> findRowCol(pair<string,string>pairs,set<string> &vertex){
set<string>::iterator it;
int row,col;
int count=0;
for(it=vertex.begin();it!=vertex.end();it++,count++){
if(*it==pairs.first)
{row=count;}
else if(*it==pairs.second){
col=count;
}
}
vector<int> result;
result.push_back(row);
result.push_back(col);
return result;
}
void printGraph(){
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
cout<<edges[i][j]<<" ";
}
cout<<endl;
}
}
void DFSTraverse(int vertexNum,int which,int end){
if(which==end){
return ;
}
visited[which]=true;
int j;
for(j=0;j<vertexNum;j++){
if(edges[which][j]!=MAXVALUE&&!visited[j]){
final[j]=final[which]*edges[which][j];
DFSTraverse(vertexNum, j,end);
}
}
}
vector<double> calcEquation(vector<pair<string, string>>equations, vector<double>& values, vector<pair<string, string>> queries) {
//build the directed graph
set<string> vertex;
vector <double> result;
for(int i=0;i<equations.size();i++){
vertex.insert(equations[i].first);
vertex.insert(equations[i].second);
}
int vertexNum=vertex.size();
int edgeNum=values.size();
memset(edges, MAXVALUE, sizeof(edges));
memset(visited,false,sizeof(visited));
memset(final,1.0,sizeof(final));
vector<int> rowCol;
for(int i=0;i<equations.size();i++){
rowCol=findRowCol(equations[i], vertex);
int row=rowCol[0];
int col=rowCol[1];
edges[row][col]=values[i];
edges[col][row]=1.0/values[i];
}
// finished build the directed graph;
//printGraph();
for(int i=0;i<queries.size();i++){
rowCol=findRowCol(queries[i], vertex);
int row=rowCol[0];
int col=rowCol[1];
DFSTraverse(vertexNum,row,col);
if(visited[col]==false)
{result.push_back(-1.0);
cout<<-1.0<<endl;}
else
{result.push_back(final[col]);
cout<<final[col]<<endl;}
}
return result;
}
};
int main(){
Solution *test=new Solution();
vector<pair<string, string>> equations;
vector<pair<string, string>> queries;
pair<string,string> test1("a","b");
pair<string,string> test2("b","c");
pair<string,string> test3("a","c");
equations.push_back(test1);
equations.push_back(test2);
vector<double> values;
values.push_back(2.0);
values.push_back(3.0);
queries.push_back(test3);
test->calcEquation(equations,values,queries);
return 0;
}