#include<vector> classSolution { public: vector<long> s; long maxv = 0; // value for root only longdfs(TreeNode* root)// 计算子树和 { long max = 0; if(root) { long left = dfs(root->left); long right = dfs(root->right); max = left+right+root->val; if(max > maxv) { maxv = max; //root node cnt } s.push_back(max); return max; } return0;
}
intmaxProduct(TreeNode* root)// 计算最大乘积 { dfs(root); // get s int i = 0; longlong max = 0; longlong res = 0; longlong mod = 1e9+7; for(i=0;i<s.size();i++) { long res = (maxv - s[i])*s[i]; if(res>max) { max = res; } } return max%mod; }
#include<iostream> constexpr auto MAXNODE = 100;; short graph[MAXNODE][MAXNODE]; short mark[MAXNODE]; // mark表示自己是否是一个节点的下属 int flag = 0; using namespace std;
intdfs(int start, int count,int father) { // 遍历,start表示开始的下标,count是目前已经有多少节点 // 返回:最大路径长度 int i = 0; int max = count; for (i = 0; i < MAXNODE; i++) {
if (i == father) { continue; } if (graph[start][i] == 1) { // 说明这里是reachable的 // 接下来检查是不是以前就是后继 if (mark[i] == true) { flag = true; // flag = true说明不合法 return count; } // 到这里,这个节点是合法的 mark[i] = 1; // 之后dfs这个节点如果发现途中有mark=1的说明出错了 count = dfs(i, count + 1,start); mark[i] = 0; if (max < count) { max = count; } } } return max; }
intmain() { int node_cnt = 0; int cons_cnt = 0; cin >> node_cnt >> cons_cnt; int i = 0; int left = 0; int right = 0; char op; // 创建图 for (i = 0; i < cons_cnt; i++) { cin >> left >> op >> right; if (op == '<') { graph[right][left] = 1; } elseif (op == '>') { graph[left][right] = 1; } else// op is = { graph[right][left] = 1; // 等号是2 graph[left][right] = 1; } }
//从第一个节点开始遍历,检查是否有环,以及是否能all reach int count = 0; int tmp_count = 0; int max = 0; for (i = 0; i < MAXNODE; i++) { count = dfs(i, tmp_count,i); if (max < count) { max = count; } } if (flag) { cout << "信息包含冲突" << endl; return0; }