int Discrete::find_max_product_without_one(vector<int> &arr) { // vector<int> leftproduct(arr.size(), 1), rightproduct(arr.size(), 1); // for (int i=1; i<arr.size(); i++) // { // leftproduct[i]=leftproduct[i-1]*arr[i-1]; // } // for (int i=arr.size()-2; i>=0; i++) // { // rightproduct[i]=rightproduct[i]*arr[i+1]; // } // int maxV = leftproduct[0]*rightproduct[0]; // for (int i=1; i<arr.size(); i++) // maxV = max(maxV, leftproduct[i]*rightproduct[i]); // return maxV; vector<int> leftproduct, rightproduct(arr.size()); partial_sum(arr.begin(), arr.end(), back_inserter(leftproduct), multiplies<int>()); partial_sum(arr.begin(), arr.end(), rightproduct.rbegin(), multiplies<int>()); int maxproduct=INT_MAX; for (int i=0; i<arr.size(); i++) { maxproduct=max(maxproduct, (i==0 ? 1: leftproduct[i-1])* (i==arr.size()-1 ? 1: rightproduct[i+1])); } return maxproduct; }
int RandomNumber(double* probabilities, int count) { std::vector<double> cumulative; partial_sum(&probabilities[0],&probabilities[0] + count-1, back_inserter(cumulative)); boost::uniform_real<> dist(0, cumulative.back()); boost::variate_generator<boost::mt19937&, boost::uniform_real<> > die(MathFunctions::boostRandomSeed, dist); int i = (std::lower_bound(cumulative.begin(), cumulative.end(), die()) - cumulative.begin()); return i; }
int CategoricalSample(const vector<double> &vec) { vector<double> cumulative; partial_sum(vec.begin(), vec.end(), back_inserter(cumulative)); boost::uniform_real<> dist(0, cumulative.back()); boost::variate_generator<boost::mt19937&, boost::uniform_real<> > sample( gen, dist); return lower_bound(cumulative.begin(), cumulative.end(), sample()) - cumulative.begin(); }
int maxProfit(vector<int> &prices) { int ret = 0, n = (int)prices.size(); reverse(begin(prices), end(prices)); partial_sum(begin(prices), end(prices), rmx, [](int a, int b) { return a < b ? b : a; }); for (int i=n-1; i>=0; --i) ret = max(ret, rmx[i]-prices[i]); return ret; }
int minPathSum(vector<vector<int>>& grid) { // calculate the first row partial_sum( grid[0].begin(),grid[0].end(),grid[0].begin()); for (int i=1;i<grid.size();i++) { // calculate the first column grid[i][0]+=grid[i-1][0]; for(int j=1;j<grid[i].size();j++) grid[i][j]+=min(grid[i][j-1],grid[i-1][j]); } return grid[grid.size()-1][grid[grid.size()-1].size()-1]; }
int main () { vector <int> v1 (10); iota (v1.begin (), v1.end (), 0); vector <int> v2 (v1.size()); partial_sum (v1.begin (), v1.end (), v2.begin ()); ostream_iterator <int> iter (cout, " "); copy (v1.begin (), v1.end (), iter); cout << endl; copy (v2.begin (), v2.end (), iter); cout << endl; return 0; }
// rearrange unselected shapes in random sequence bool Model::AutoArrange(vector<Gtk::TreeModel::Path> &path) { // all shapes vector<Shape*> allshapes; vector<Matrix4d> transforms; objtree.get_all_shapes(allshapes, transforms); // selected shapes vector<Shape*> selshapes; vector<Matrix4d> seltransforms; objtree.get_selected_shapes(path, selshapes, seltransforms); // get unselected shapes vector<Shape*> unselshapes; vector<Matrix4d> unseltransforms; for(uint s=0; s < allshapes.size(); s++) { bool issel = false; for(uint ss=0; ss < selshapes.size(); ss++) if (selshapes[ss] == allshapes[s]) { issel = true; break; } if (!issel) { unselshapes. push_back(allshapes[s]); unseltransforms.push_back(transforms[s]); } } // find place for unselected shapes int num = unselshapes.size(); vector<int> rand_seq(num,1); // 1,1,1... partial_sum(rand_seq.begin(), rand_seq.end(), rand_seq.begin()); // 1,2,3,...,N Glib::TimeVal timeval; timeval.assign_current_time(); srandom((unsigned long)(timeval.as_double())); random_shuffle(rand_seq.begin(), rand_seq.end()); // shuffle for(int s=0; s < num; s++) { int index = rand_seq[s]-1; // use selshapes as vector to fill up Vector3d trans = FindEmptyLocation(selshapes, seltransforms, unselshapes[index]); selshapes.push_back(unselshapes[index]); seltransforms.push_back(unseltransforms[index]); // basic transform, not shape selshapes.back()->transform3D.move(trans); CalcBoundingBoxAndCenter(); } ModelChanged(); return true; }
int subarraySumII(vector<int>& A, int start, int end) { int len = A.size(); vector<int> sums(len + 1); partial_sum(A.begin(), A.end(), sums.begin() + 1); int count = 0; for (int i = 0; i < sums.size(); i++) { auto left = lower_bound(sums.begin(), sums.begin() + i, sums[i] - end); auto right = upper_bound(sums.begin(), sums.begin() + i, sums[i] - start); count += right - left; } return count; }
void construct() { P.push_back(vi(n, 0)); compress(); vi occ(n + 1, 0), s1(n, 0), s2(n, 0); for (int k = 1, cnt = 1; cnt / 2 < n; ++k, cnt *= 2) { P.push_back(vi(n, 0)); fill(occ.begin(), occ.end(), 0); for (int i = 0; i < n; ++i) occ[i+cnt<n ? P[k-1][i+cnt]+1 : 0]++; partial_sum(occ.begin(), occ.end(), occ.begin()); for (int i = n - 1; i >= 0; --i) s1[--occ[i+cnt<n ? P[k-1][i+cnt]+1 : 0]] = i; fill(occ.begin(), occ.end(), 0); for (int i = 0; i < n; ++i) occ[P[k-1][s1[i]]]++; partial_sum(occ.begin(), occ.end(), occ.begin()); for (int i = n - 1; i >= 0; --i) s2[--occ[P[k-1][s1[i]]]] = s1[i]; for (int i = 1; i < n; ++i) { P[k][s2[i]] = same(s2[i], s2[i - 1], k, cnt) ? P[k][s2[i - 1]] : i; } } }
//数值算法 void stl_numeric_algo(){ double array[] = {-2,2,4,4,5}; double array1[] = {2,3,4,5,6}; vector<double> a(array,array + sizeof(array)/sizeof(double)); vector<double> b(array1,array1 + sizeof(array1)/sizeof(double)); vector<double> result(10); cout<<"accumulate func: "<<accumulate(a.begin(), a.end(), 0, minus<double>())<<endl; cout<<"inner product func: "<<inner_product(a.begin(),a.end(),b.begin(),0.0,plus<double>(),multiplies<double>())<<endl; adjacent_difference(a.begin(),a.end(),result.begin()); cout<<"adjacent_difference : "<<result<<endl; partial_sum(result.begin(),result.end(),result.begin()); cout<<"partial_sum : "<<result<<endl; ostream_iterator<double> myout(cout, " "); copy(result.begin(), result.end(), myout); }
int main(void){ std::ifstream in; in.open("program.txt"); std::ofstream log; log.open("calculator.log"); std::ofstream err; err.open("debug.log"); Scanner scan{in}; Calculator calc{scan}; std::streambuf *logbuff = std::clog.rdbuf(log.rdbuf()); std::streambuf *errbuff = std::cerr.rdbuf(err.rdbuf()); while(calc.run(std::cout, std::clog)); auto vars = calc.get_table(); auto var_end = remove_if(begin(vars), end(vars), [](Calculator::symbol_t& a){return !a.writen;}); //std::cout << vars << std::endl; std::cout << std::endl << "Variable Statistics: " << std::endl; // print the things in alphabetical order sort(begin(vars), var_end); for_each(begin(vars), var_end, [](Calculator::symbol_t& a){std::cout << a << std::endl;}); std::cout << "Number of variable names > m: " << count_if(begin(vars), var_end, [](Calculator::symbol_t& a){return a.name > "m";}) << std::endl; std::cout << "Minimum element value: " << *min_element(begin(vars), var_end, val_comp) << std::endl; std::cout << "Maximum element value: " << *max_element(begin(vars), var_end, val_comp) << std::endl; std::cout << "Any of the elements have a value > 50? " <<std::boolalpha<< any_of(begin(vars), var_end, [](Calculator::symbol_t& a){return a.val > 50;}) << std::endl; std::cout << "Print the first variable found between i and n: " << *find_if(begin(vars), var_end, [](Calculator::symbol_t& a){return a.name > "i"&&a.name<"n";}) << std::endl; std::cout << "Increase every value of the table by 5: " << std::endl;// (hint transform) for_each(begin(vars), var_end, [](Calculator::symbol_t& a){a.val+=5;}); for_each(begin(vars), var_end, [](Calculator::symbol_t& a){std::cout << a << std::endl;}); std::cout << "Sort the table entries by value (not by variable name): " << std::endl; sort(begin(vars), var_end, val_comp); for_each(begin(vars), var_end, [](Calculator::symbol_t& a){std::cout << a << std::endl;}); std::cout << "Show the partial sum of all values in the table: " << std::endl; std::vector<Calculator::symbol_t> part_sums; partial_sum(begin(vars), var_end, back_inserter(part_sums)); for_each(begin(part_sums), end(part_sums), [](Calculator::symbol_t& a){std::cout << a << std::endl;}); in.close(); log.close(); err.close(); std::clog.rdbuf(logbuff); std::cerr.rdbuf(errbuff); return 0; }
int minSubArrayLen(int s, vector<int>& nums) { if (nums.empty()) return 0; vector<int> sums(nums.size(), 0); partial_sum(nums.begin(), nums.end(), sums.begin()); int n = nums.size(), minlen = n + 1; for (int i = 0; i < n; i++) { if (sums[i] >= s) { auto p = upper_bound(sums.begin(), sums.begin() + i, sums[i] - s); if (p != sums.begin() + 1) { minlen = min(minlen, i - (p - sums.begin()) + 1); } } } return minlen == n + 1 ? 0 : minlen; }
vector<int> solution(string &S, vector<int> &P, vector<int> &Q) { vector<vector<int>> parsums(4); for_each(parsums.begin(), parsums.end(), [&S](vector<int>& x) { x.resize(S.size()); }); for (unsigned i = 0; i < S.size(); ++i) { auto t = [=](char c) -> int { switch (c) { case 'A': return 0; case 'C': return 1; case 'G': return 2; default: return 3; } }; parsums[t(S[i])][i] = 1; } for_each(parsums.begin(), parsums.end(), [](vector<int>& x) { partial_sum(x.begin(), x.end(), x.begin()); }); vector<int> result(P.size()); for (unsigned i = 0; i < P.size(); ++i) { int type = 3; for (unsigned j = 0; j < 3; ++j) { auto left = P[i] > 0 ? parsums[j][P[i] - 1] : 0; auto right = parsums[j][Q[i]]; if (right != left) { type = j; break; } } result[i] = type + 1; } }
int minSubArrayLen(int s, vector<int>& nums) { int min_size = numeric_limits<int>::max(); vector<int> sum_from_start(nums.size() + 1); partial_sum(nums.cbegin(), nums.cend(), sum_from_start.begin() + 1); for (int i = 0; i < nums.size(); ++i) { const auto& end_it = lower_bound(sum_from_start.cbegin() + i, sum_from_start.cend(), sum_from_start[i] + s); if (end_it != sum_from_start.cend()) { int end = static_cast<int>(end_it - sum_from_start.cbegin()); min_size = min(min_size, end - i); } } if (min_size == numeric_limits<int>::max()) { return 0; } return min_size; }
void Misc::findContinuousSequence(const vector<int> &A, int k) { vector<int> psum; partial_sum(A.begin(), A.end(), back_inserter(psum)); int left=0, right=1; while( right < A.size() && left <= right) { int sum=psum[right]-psum[left]+A[left]; if (sum==k) { printVector(vector<int>(A.begin()+left, A.begin()+right+1)); left++; right++; } else if (sum<k) { right++; } else left++; } }
int shortestSubarray(vector<int>& A, int K) { vector<int> accumulated_sum(A.size() + 1, 0); partial_sum(A.cbegin(), A.cend(), next(accumulated_sum.begin()), plus<int>()); int result = numeric_limits<int>::max(); deque<int> mono_increasing_q; for (int i = 0; i < accumulated_sum.size(); ++i) { while (!mono_increasing_q.empty() && accumulated_sum[i] <= accumulated_sum[mono_increasing_q.back()]) { mono_increasing_q.pop_back(); } while (!mono_increasing_q.empty() && accumulated_sum[i] - accumulated_sum[mono_increasing_q.front()] >= K) { result = min(result, i - mono_increasing_q.front()); mono_increasing_q.pop_front(); } mono_increasing_q.emplace_back(i); } return result != numeric_limits<int>::max() ? result : -1; }
int subarraySumII(vector<int>& A, int start, int end) { int len = A.size(); if (len == 0) { return 0; } vector<int> sums(len + 1); partial_sum(A.begin(), A.end(), sums.begin() + 1); int count = 0; for (int i = 0; i < sums.size()-1; i++) { for (int j = i+1; j < sums.size(); j++) { int rangeSum = sums[j] - sums[i]; if (rangeSum >= start && rangeSum <= end) { count++; } } } return count; }
int NonuniformRandomNumberGeneration::nonuniformRandomNumberGeneration( const vector<int> &values, const vector<double> &probabilities) { if (values.size() != probabilities.size()) { throw invalid_argument("Not all values have probabilities or move probabilities than values."); } vector<double> prefixSumOfProbabilities; prefixSumOfProbabilities.push_back(0.0); partial_sum( probabilities.cbegin(), probabilities.cend(), back_inserter(prefixSumOfProbabilities) ); default_random_engine seed( (random_device()) () ); double uniform_0_1 = generate_canonical< double, numeric_limits<double>::digits >(seed); int intervalIdx = distance( prefixSumOfProbabilities.cbegin(), upper_bound(prefixSumOfProbabilities.cbegin(), prefixSumOfProbabilities.cend(), uniform_0_1) ) - 1; if ( intervalIdx >= static_cast<int>(values.size()) ) { throw runtime_error("Index " + to_string(intervalIdx) + " out of bound."); } return values[intervalIdx]; }
void SpParHelper::BipartiteSwap(pair<KEY,VAL> * low, pair<KEY,VAL> * array, IT length, int nfirsthalf, int color, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); IT * firsthalves = new IT[nprocs]; IT * secondhalves = new IT[nprocs]; firsthalves[myrank] = low-array; secondhalves[myrank] = length - (low-array); MPI_Allgather(MPI_IN_PLACE, 0, MPIType<IT>(), firsthalves, 1, MPIType<IT>(), comm); MPI_Allgather(MPI_IN_PLACE, 0, MPIType<IT>(), secondhalves, 1, MPIType<IT>(), comm); int * sendcnt = new int[nprocs](); // zero initialize int totrecvcnt = 0; pair<KEY,VAL> * bufbegin = NULL; if(color == 0) // first processor half, only send second half of data { bufbegin = low; totrecvcnt = length - (low-array); IT beg_oftransfer = accumulate(secondhalves, secondhalves+myrank, static_cast<IT>(0)); IT spaceafter = firsthalves[nfirsthalf]; int i=nfirsthalf+1; while(i < nprocs && spaceafter < beg_oftransfer) { spaceafter += firsthalves[i++]; // post-incremenet } IT end_oftransfer = beg_oftransfer + secondhalves[myrank]; // global index (within second half) of the end of my data IT beg_pour = beg_oftransfer; IT end_pour = min(end_oftransfer, spaceafter); sendcnt[i-1] = end_pour - beg_pour; while( i < nprocs && spaceafter < end_oftransfer ) // find other recipients until I run out of data { beg_pour = end_pour; spaceafter += firsthalves[i]; end_pour = min(end_oftransfer, spaceafter); sendcnt[i++] = end_pour - beg_pour; // post-increment } } else if(color == 1) // second processor half, only send first half of data { bufbegin = array; totrecvcnt = low-array; // global index (within the second processor half) of the beginning of my data IT beg_oftransfer = accumulate(firsthalves+nfirsthalf, firsthalves+myrank, static_cast<IT>(0)); IT spaceafter = secondhalves[0]; int i=1; while( i< nfirsthalf && spaceafter < beg_oftransfer) { //spacebefore = spaceafter; spaceafter += secondhalves[i++]; // post-increment } IT end_oftransfer = beg_oftransfer + firsthalves[myrank]; // global index (within second half) of the end of my data IT beg_pour = beg_oftransfer; IT end_pour = min(end_oftransfer, spaceafter); sendcnt[i-1] = end_pour - beg_pour; while( i < nfirsthalf && spaceafter < end_oftransfer ) // find other recipients until I run out of data { beg_pour = end_pour; spaceafter += secondhalves[i]; end_pour = min(end_oftransfer, spaceafter); sendcnt[i++] = end_pour - beg_pour; // post-increment } } DeleteAll(firsthalves, secondhalves); int * recvcnt = new int[nprocs]; MPI_Alltoall(sendcnt, 1, MPI_INT, recvcnt, 1, MPI_INT, comm); // get the recv counts // Alltoall is actually unnecessary, because sendcnt = recvcnt // If I have n_mine > n_yours data to send, then I can send you only n_yours // as this is your space, and you'll send me identical amount. // Then I can only receive n_mine - n_yours from the third processor and // that processor can only send n_mine - n_yours to me back. // The proof follows from induction MPI_Datatype MPI_valueType; MPI_Type_contiguous(sizeof(pair<KEY,VAL>), MPI_CHAR, &MPI_valueType); MPI_Type_commit(&MPI_valueType); pair<KEY,VAL> * receives = new pair<KEY,VAL>[totrecvcnt]; int * sdpls = new int[nprocs](); // displacements (zero initialized pid) int * rdpls = new int[nprocs](); partial_sum(sendcnt, sendcnt+nprocs-1, sdpls+1); partial_sum(recvcnt, recvcnt+nprocs-1, rdpls+1); MPI_Alltoallv(bufbegin, sendcnt, sdpls, MPI_valueType, receives, recvcnt, rdpls, MPI_valueType, comm); // sparse swap DeleteAll(sendcnt, recvcnt, sdpls, rdpls); copy(receives, receives+totrecvcnt, bufbegin); delete [] receives; }
void SpParHelper::GlobalSelect(IT gl_rank, pair<KEY,VAL> * & low, pair<KEY,VAL> * & upp, pair<KEY,VAL> * array, IT length, const MPI_Comm & comm) { int nprocs, myrank; MPI_Comm_size(comm, &nprocs); MPI_Comm_rank(comm, &myrank); IT begin = 0; IT end = length; // initially everyone is active pair<KEY, double> * wmminput = new pair<KEY,double>[nprocs]; // (median, #{actives}) MPI_Datatype MPI_sortType; MPI_Type_contiguous (sizeof(pair<KEY,double>), MPI_CHAR, &MPI_sortType); MPI_Type_commit (&MPI_sortType); KEY wmm; // our median pick IT gl_low, gl_upp; IT active = end-begin; // size of the active range IT nacts = 0; bool found = 0; int iters = 0; /* changes by shan : to add begin0 and end0 for exit condition */ IT begin0, end0; do { iters++; begin0 = begin; end0 = end; KEY median = array[(begin + end)/2].first; // median of the active range wmminput[myrank].first = median; wmminput[myrank].second = static_cast<double>(active); MPI_Allgather(MPI_IN_PLACE, 0, MPI_sortType, wmminput, 1, MPI_sortType, comm); double totact = 0; // total number of active elements for(int i=0; i<nprocs; ++i) totact += wmminput[i].second; // input to weighted median of medians is a set of (object, weight) pairs // the algorithm computes the first set of elements (according to total // order of "object"s), whose sum is still less than or equal to 1/2 for(int i=0; i<nprocs; ++i) wmminput[i].second /= totact ; // normalize the weights sort(wmminput, wmminput+nprocs); // sort w.r.t. medians double totweight = 0; int wmmloc=0; while( wmmloc<nprocs && totweight < 0.5 ) { totweight += wmminput[wmmloc++].second; } wmm = wmminput[wmmloc-1].first; // weighted median of medians pair<KEY,VAL> wmmpair = make_pair(wmm, VAL()); low =lower_bound (array+begin, array+end, wmmpair); upp =upper_bound (array+begin, array+end, wmmpair); IT loc_low = low-array; // #{elements smaller than wmm} IT loc_upp = upp-array; // #{elements smaller or equal to wmm} MPI_Allreduce( &loc_low, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); MPI_Allreduce( &loc_upp, &gl_upp, 1, MPIType<IT>(), MPI_SUM, comm); if(gl_upp < gl_rank) { // our pick was too small; only recurse to the right begin = (low - array); } else if(gl_rank < gl_low) { // our pick was too big; only recurse to the left end = (upp - array); } else { found = true; } active = end-begin; MPI_Allreduce(&active, &nacts, 1, MPIType<IT>(), MPI_SUM, comm); if (begin0 == begin && end0 == end) break; // ABAB: Active range did not shrink, so we break (is this kosher?) } while((nacts > 2*nprocs) && (!found)); delete [] wmminput; MPI_Datatype MPI_pairType; MPI_Type_contiguous (sizeof(pair<KEY,VAL>), MPI_CHAR, &MPI_pairType); MPI_Type_commit (&MPI_pairType); int * nactives = new int[nprocs]; nactives[myrank] = static_cast<int>(active); // At this point, actives are small enough MPI_Allgather(MPI_IN_PLACE, 0, MPI_INT, nactives, 1, MPI_INT, comm); int * dpls = new int[nprocs](); // displacements (zero initialized pid) partial_sum(nactives, nactives+nprocs-1, dpls+1); pair<KEY,VAL> * recvbuf = new pair<KEY,VAL>[nacts]; low = array + begin; // update low to the beginning of the active range MPI_Allgatherv(low, active, MPI_pairType, recvbuf, nactives, dpls, MPI_pairType, comm); pair<KEY,int> * allactives = new pair<KEY,int>[nacts]; int k = 0; for(int i=0; i<nprocs; ++i) { for(int j=0; j<nactives[i]; ++j) { allactives[k] = make_pair(recvbuf[k].first, i); k++; } } DeleteAll(recvbuf, dpls, nactives); sort(allactives, allactives+nacts); MPI_Allreduce(&begin, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); // update int diff = gl_rank - gl_low; for(int k=0; k < diff; ++k) { if(allactives[k].second == myrank) ++low; // increment the local pointer } delete [] allactives; begin = low-array; MPI_Allreduce(&begin, &gl_low, 1, MPIType<IT>(), MPI_SUM, comm); // update }
NumArray(vector<int> &nums):psum(nums.size()+1,0) { //psum[0]=0; partial_sum(nums.begin(),nums.end(),psum.begin()+1); }