111)计算除法
class Solution{
public:
vector<double> calcEquation(vector<vector<string>>& equations, vector<double>& values, vector<vector<string>>& queries){
int nvars = 0;
unordered_map<string, int> variables;
int n = equations.size();
for(int i=0; i<n; i++){
if(variables.find(equations[i][0]) == variables.end()){
variables[equations[i][0]] = nvars++;
}
if(variables.find(equations[i][1]) == variables.end()){
variables[equations[i][1]] = nvars++;
}
}
vector<vector<pair<int, double>>> edges(nvars);
for(int i=0; i<n; i++){
int va=variables[equations[i][0]], vb=variables[equations[i][1]];
edges[va].push_back(make_pair(vb, values[i]));
edges[vb].push_back(make_pair(va, 1.0 / values[i]));
}
vector<double> ret;
for(auto& q : queries){
double result = -1.0;
if(variables.find(q[0]) != variables.end() && variables.find(q[1]) != variables.end()){
int ia = variables[q[0]], ib = variables[q[1]];
if(ia==ib) result = 1.0;
else{
queue<int> points;
points.push(ia);
vector<double> ratios(nvars, -1.0);
ratios[ia] = 1.0;
while(!points.empty() && ratios[ib]<0){
int x = points.front();
points.pop();
for(auto [y, val] : edges[x]){
if(ratios[y]<0) {
ratios[y] = ratios[x] * val;
points.push(y);
}
}
}
result = ratios[ib];
}
}
ret.push_back(result);
}
return ret;
}
};
class Solution{
public:
int rows, cols;
int dirs[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int longestIncreasingPath(vector<vector<int>>& matrix){
if(!matrix.size() || !matrix[0].size()) return 0;
rows = matrix.size(), cols = matrix[0].size();
int ans = 0;
vector<vector<int>> res(rows, vector<int>(cols));
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
ans = max(ans, dfs(matrix, i, j, res));
}
}
return ans;
}
int dfs(vector<vector<int>>& matrix, int row, int col, vector<vector<int>>& res){
if(res[row][col] != 0) return res[row][col];
res[row][col]++;
for(int i=0; i<4; i++){
int newrow = row+dirs[i][0], newcol = col+dirs[i][1];
if(newrow>=0 && newcol>=0 && newrow<rows && newcol<cols && matrix[newrow][newcol] > matrix[row][col])
res[row][col] = max(res[row][col], dfs(matrix, newrow, newcol, res)+1);
}
return res[row][col];
}
};
113)课程顺序(课程表II)
class Solution{
public:
vector<int> findOrder(int numCourses, vector<vector<int>>& prerequisites){
vector<vector<int>> edges(numCourses);
vector<int> indegree(numCourses);
for(auto &item : prerequisites){
edges[item[1]].push_back(item[0]);
indegree[item[0]]++;
}
queue<int> q;
for(int i=0; i<numCourses; i++){
if(!indegree[i]) q.push(i);
}
vector<int> res;
while(!q.empty()){
int x = q.front();
q.pop();
res.push_back(x);
for(auto y : edges[x]){
indegree[y]--;
if(indegree[y]==0){
q.push(y);
}
}
}
return res.size()==numCourses ? res : vector<int>{};
}
};