Sunday, January 5, 2020

C++ tips

1. Minimum Priority Queue - int
 priority_queue<int, vector<int>, greater<int>> q;  

2. Minimum Priotity Queue - Struct
 struct Interval {  
      int start, end, num;  
      bool operator < (const Interval &a)const {  
           return end>a.end;  
      }  
 }  
 bool comp(Interval a, Interval b)  
 {  
      if (a.start == b.start) {  
           return a.end < b.end;  
      }  
      else return a.start < b.start;  
 }  
 priority_queue<Interval> q;  

3. MOD
 static int MOD = 1000000007;  
 class Solution {  
 public:  
      ll total = 0;  
      ll ansMax = 0;  
      vector<ll> sums;  
      long long sumTree(TreeNode *root) {  
           if (root == NULL) return 0;  
           ll subsum = (root->val + sumTree(root->left) + sumTree(root->right));  
           sums.push_back(subsum);  
           return subsum;  
      }  
      int maxProduct(TreeNode* root) {  
           total = sumTree(root);  
           ll ans = 0;  
           for (int i = 0; i < sums.size(); i++) {  
                ll prod = (total - sums[i]) * sums[i];  
                ans = max(ans, prod);  
           }  
           return ans % MOD;  
      }  
 };  

4.String
 // extract to string  
 #include <iostream>  
 #include <string>  
 int main ()  
 {  
  std::string name;  
  std::getline (std::cin,name);  
 }  

5.Lower_bound
  std::vector<int>::iterator low,up;  
  // returns first equal or greater elements location (or returns end if not found)
  low=std::lower_bound (v.begin(), v.end(), 20); 
  up= std::upper_bound (v.begin(), v.end(), 20);  
  std::cout << "lower_bound at position " << (low- v.begin()) << '\n';  
  std::cout << "upper_bound at position " << (up - v.begin()) << '\n';  
  std::cout << "lower_bound at position " << (up - low) << '\n';  

5.String
 #include<string>  
 #include<sstream>  
 int main()  
 {  
      string str, line;  
      while (getline(cin, line)) {  
           istringstream input(line);  
           while (input >> str) {  
             //str process here  
           }  
      }  
      return 0;  
 }  

No comments:

Post a Comment