fork download
  1. // Online C++ compiler to run C++ program online
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4.  
  5. int binSearchInd(vector<long> population, int randInd) {
  6. int low = 0;
  7. int high = population.size();
  8.  
  9. while (low <= high) {
  10. int mid = (low + high)/2;
  11. if ((mid==0 && population[mid] >= randInd) || (population[mid-1] < randInd && population[mid] >= randInd)) {//out of ind
  12. return mid;
  13. } else if (population[mid] < randInd) {
  14. low = mid + 1;
  15. } else {
  16. high = mid-1;
  17. }
  18.  
  19. }
  20. return -1;
  21. }
  22.  
  23. string randCity(vector<string> cities, vector<long> population) {
  24. vector<long> preSum;
  25. preSum.push_back(population[0]);
  26.  
  27. int size = population.size();
  28.  
  29. for (int i = 1; i < size; i++) {
  30. preSum.push_back(preSum.back() + population[i]);
  31. }
  32.  
  33. int randInd = 1 + rand() % (preSum.back());
  34.  
  35.  
  36. int cityInd = binSearchInd(preSum, randInd);
  37. cout<<rand()<<" "<<randInd<<" "<<cityInd<<endl;
  38. return cities[cityInd];
  39. }
  40.  
  41. int main() {
  42. // Write C++ code here
  43. vector<string> cities = {"A", "B", "C", "D"};
  44. vector<long> population = {5, 4, 2, 6};
  45. cout<<randCity(cities, population)<<endl;
  46.  
  47. return 0;
  48. }
  49.  
  50.  
Success #stdin #stdout 0.01s 5284KB
stdin
10
aba
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
geeksforgeeks
stdout
846930886 11 2
C