<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/predictor/vehicle/lane_sequence_predictor.h"

#include <cmath>
#include <utility>
#include <limits>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::math::KalmanFilter;
using ::apollo::common::adapter::AdapterConfig;

void LaneSequencePredictor::Clear() {
  trajectories_.clear();
  adc_lane_id_.clear();
  adc_lane_s_ = 0.0;
}

void LaneSequencePredictor::Predict(Obstacle* obstacle) {
  Clear();

  CHECK_NOTNULL(obstacle);
  CHECK_GT(obstacle->history_size(), 0);

  const Feature& feature = obstacle->latest_feature();
  if (!feature.has_lane() || !feature.lane().has_lane_graph()) {
    AERROR << "Obstacle [" << obstacle->id() << " has no lane graph.";
    return;
  }

  std::string lane_id = "";
  if (feature.lane().has_lane_feature()) {
    lane_id = feature.lane().lane_feature().lane_id();
  }
  int num_lane_sequence = feature.lane().lane_graph().lane_sequence_size();
  std::vector<bool> enable_lane_sequence(num_lane_sequence, true);
  FilterLaneSequences(feature.lane().lane_graph(),
                      lane_id,
                      &enable_lane_sequence);

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = feature.lane().lane_graph().lane_sequence(i);
    if (sequence.lane_segment_size() <= 0) {
      AERROR << "Empty lane segments.";
      continue;
    }

    if (!enable_lane_sequence[i]) {
      ADEBUG << "Lane sequence [" << ToString(sequence)
             << "] with probability ["
             <<sequence.probability() << "] is disqualified.";
      continue;
    }

    ADEBUG << "Obstacle [" << obstacle->id()
           << "] will draw a lane sequence trajectory ["
           << ToString(sequence) << "] with probability ["
           << sequence.probability() << "].";

    std::string curr_lane_id = sequence.lane_segment(0).lane_id();
    std::vector<TrajectoryPoint> points;
    DrawLaneSequenceTrajectoryPoints(
        obstacle->kf_lane_tracker(curr_lane_id), sequence,
        FLAGS_prediction_duration, FLAGS_prediction_freq, &points);

    Trajectory trajectory;
    GenerateTrajectory(points, &trajectory);
    trajectory.set_probability(sequence.probability());
    trajectories_.push_back(std::move(trajectory));
  }
  ADEBUG << "Obstacle [" << obstacle->id()
         << "] has total " << trajectories_.size()
         << " trajectories.";
}

void LaneSequencePredictor::FilterLaneSequences(
    const LaneGraph& lane_graph,
    const std::string& lane_id,
    std::vector<bool> *enable_lane_sequence) {
  int num_lane_sequence = lane_graph.lane_sequence_size();
  std::vector<int> lane_change_type(num_lane_sequence, -1);
  std::pair<int, double> change(-1, -1.0);
  std::pair<int, double> all(-1, -1.0);

  // Get ADC status
  GetADC();

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    // Get lane change type
    lane_change_type[i] = GetLaneChangeType(lane_id, sequence);

    double probability = sequence.probability();

    if (::apollo::common::math::DoubleCompare(probability, all.second) > 0 ||
        (::apollo::common::math::DoubleCompare(probability, all.second) == 0 &&
         lane_change_type[i] == 0)) {
      all.first = i;
      all.second = probability;
    }
    if (lane_change_type[i] > 0 &&
        ::apollo::common::math::DoubleCompare(probability, change.second) > 0) {
      change.first = i;
      change.second = probability;
    }
  }

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    // The obstacle has interference with ADC within a small distance
    if (::apollo::common::math::DoubleCompare(
        GetLaneChangeDistanceWithADC(sequence), FLAGS_lane_change_dist) < 0) {
      (*enable_lane_sequence)[i] = false;
      continue;
    }

    double probability = sequence.probability();
    if (::apollo::common::math::DoubleCompare(
        probability, FLAGS_lane_sequence_threshold) < 0 &&
        i != all.first) {
      (*enable_lane_sequence)[i] = false;
    } else if (change.first >= 0 &&
               change.first < num_lane_sequence &&
               lane_change_type[i] > 0 &&
               lane_change_type[i] != lane_change_type[change.first]) {
      (*enable_lane_sequence)[i] = false;
    }
  }
}

void LaneSequencePredictor::GetADC() {
  ObstaclesContainer *container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  if (container == nullptr) {
    AERROR << "Unavailable obstacle container";
    return;
  }

  Obstacle *adc = container->GetObstacle(PoseContainer::ID);
  if (adc != nullptr) {
    const Feature& feature = adc->latest_feature();
    if (feature.has_lane() &&
        feature.lane().has_lane_feature()) {
      adc_lane_id_ = feature.lane().lane_feature().lane_id();
      adc_lane_s_ = feature.lane().lane_feature().lane_s();
    }
    if (feature.has_position()) {
      adc_position_[0] = feature.position().x();
      adc_position_[1] = feature.position().y();
    }
  }
}

int LaneSequencePredictor::GetLaneChangeType(
    const std::string& lane_id,
    const LaneSequence& lane_sequence) {
  PredictionMap *map = PredictionMap::instance();

  std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
  if (lane_id == lane_change_id) {
    return 0;
  } else {
    if (map->IsLeftNeighborLane(
        map->LaneById(lane_change_id), map->LaneById(lane_id))) {
      return 1;
    } else if (map->IsRightNeighborLane(
        map->LaneById(lane_change_id), map->LaneById(lane_id))) {
      return 2;
    }
  }
  return -1;
}

double LaneSequencePredictor::GetLaneChangeDistanceWithADC(
    const LaneSequence& lane_sequence) {
  if (adc_lane_id_.empty() || lane_sequence.lane_segment_size() <= 0) {
    return std::numeric_limits<double>::max();
  }

  PredictionMap *map = PredictionMap::instance();
  std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
  double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();

  double lane_s = 0.0;
  double lane_l = 0.0;
  if (map->GetProjection(adc_position_,
                         map->LaneById(obstacle_lane_id),
                         &lane_s, &lane_l)) {
    return std::fabs(lane_s - obstacle_lane_s);
  }
  return std::numeric_limits<double>::max();
}

void LaneSequencePredictor::DrawLaneSequenceTrajectoryPoints(
    const KalmanFilter<double, 4, 2, 0>& kf,
    const LaneSequence& sequence,
    double total_time,
    double freq,
    std::vector<TrajectoryPoint> *points) {
  PredictionMap *map = PredictionMap::instance();

  Eigen::Matrix<double, 4, 1> state(kf.GetStateEstimate());
  double lane_s = state(0, 0);
  double lane_l = state(1, 0);
  double lane_speed = state(2, 0);
  double lane_acc = state(3, 0);

  Eigen::Matrix<double, 4, 4> transition(kf.GetTransitionMatrix());
  transition(0, 2) = freq;
  transition(0, 3) = 0.5 * freq * freq;
  transition(2, 3) = freq;

  int lane_segment_index = 0;
  std::string lane_id = sequence.lane_segment(lane_segment_index).lane_id();
  for (size_t i = 0; i < static_cast<size_t>(total_time / freq); ++i) {
    Eigen::Vector2d point;
    double theta = M_PI;
    if (!map->SmoothPointFromLane(lane_id, lane_s, lane_l, &point, &theta)) {
      AERROR << "Unable to get smooth point from lane [" << lane_id
             << "] with s [" << lane_s << "] and l [" << lane_l
             << "]";
      continue;
    }

    if (points->size() > 0) {
      PathPoint *prev_point = points->back().mutable_path_point();
      double x_diff = point.x() - prev_point->x();
      double y_diff = point.y() - prev_point->y();
      if (::apollo::common::math::DoubleCompare(x_diff, 0.0) != 0 ||
          ::apollo::common::math::DoubleCompare(y_diff, 0.0) != 0) {
        theta = std::atan2(y_diff, x_diff);
        prev_point->set_theta(theta);
      } else {
        theta = prev_point->theta();
      }
    }

    // add trajectory point
    TrajectoryPoint trajectory_point;
    PathPoint path_point;
    path_point.set_x(point.x());
    path_point.set_y(point.y());
    path_point.set_z(0.0);
    path_point.set_theta(theta);
    trajectory_point.mutable_path_point()->CopyFrom(path_point);
    trajectory_point.set_v(lane_speed);
    trajectory_point.set_a(lane_acc);
    trajectory_point.set_relative_time(static_cast<double>(i) * freq);
    points->emplace_back(std::move(trajectory_point));

    // update state
    if (::apollo::common::math::DoubleCompare(lane_speed, 0.0) <= 0) {
      AWARN << "Non-positive lane_speed tacked : " << lane_speed;
      lane_speed = 0.0;
      lane_acc = 0.0;
      transition(1, 1) = 1.0;
    } else if (::apollo::common::math::DoubleCompare(
        lane_speed, FLAGS_max_speed) >= 0) {
      lane_speed = FLAGS_max_speed;
      lane_acc = 0.0;
    }
    state(2, 0) = lane_speed;
    state(3, 0) = lane_acc;

    state = transition * state;
    if (::apollo::common::math::DoubleCompare(lane_s, state(0, 0)) >= 0) {
      state(0, 0) = lane_s;
      state(1, 0) = lane_l;
      state(2, 0) = 0.0;
      state(3, 0) = 0.0;
      transition(1, 1) = 1.0;
    }
    lane_s = state(0, 0);
    lane_l = state(1, 0);
    lane_speed = state(2, 0);
    lane_acc = state(3, 0);

    // find next lane id
    while (lane_s > map->LaneById(lane_id)->total_length() &&
           lane_segment_index + 1 < sequence.lane_segment_size()) {
      lane_segment_index += 1;
      lane_s = lane_s - map->LaneById(lane_id)->total_length();
      state(0, 0) = lane_s;
      lane_id = sequence.lane_segment(lane_segment_index).lane_id();
    }
  }
}

std::string LaneSequencePredictor::ToString(const LaneSequence& sequence) {
  std::string str_lane_sequence = "";
  if (sequence.lane_segment_size() > 0) {
    str_lane_sequence += sequence.lane_segment(0).lane_id();
  }
  for (int i = 1; i < sequence.lane_segment_size(); ++i) {
    str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
  }
  return str_lane_sequence;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>Prediction: fixed a minor issue<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/prediction/predictor/vehicle/lane_sequence_predictor.h"

#include <cmath>
#include <utility>
#include <limits>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/adapters/proto/adapter_config.pb.h"
#include "modules/map/hdmap/hdmap_util.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/obstacles/obstacles_container.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::math::KalmanFilter;
using ::apollo::common::adapter::AdapterConfig;

void LaneSequencePredictor::Clear() {
  trajectories_.clear();
  adc_lane_id_.clear();
  adc_lane_s_ = 0.0;
}

void LaneSequencePredictor::Predict(Obstacle* obstacle) {
  Clear();

  CHECK_NOTNULL(obstacle);
  CHECK_GT(obstacle->history_size(), 0);

  const Feature& feature = obstacle->latest_feature();
  if (!feature.has_lane() || !feature.lane().has_lane_graph()) {
    AERROR << "Obstacle [" << obstacle->id() << " has no lane graph.";
    return;
  }

  std::string lane_id = "";
  if (feature.lane().has_lane_feature()) {
    lane_id = feature.lane().lane_feature().lane_id();
  }
  int num_lane_sequence = feature.lane().lane_graph().lane_sequence_size();
  std::vector<bool> enable_lane_sequence(num_lane_sequence, true);
  FilterLaneSequences(feature.lane().lane_graph(),
                      lane_id,
                      &enable_lane_sequence);

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = feature.lane().lane_graph().lane_sequence(i);
    if (sequence.lane_segment_size() <= 0) {
      AERROR << "Empty lane segments.";
      continue;
    }

    if (!enable_lane_sequence[i]) {
      ADEBUG << "Lane sequence [" << ToString(sequence)
             << "] with probability ["
             <<sequence.probability() << "] is disqualified.";
      continue;
    }

    ADEBUG << "Obstacle [" << obstacle->id()
           << "] will draw a lane sequence trajectory ["
           << ToString(sequence) << "] with probability ["
           << sequence.probability() << "].";

    std::string curr_lane_id = sequence.lane_segment(0).lane_id();
    std::vector<TrajectoryPoint> points;
    DrawLaneSequenceTrajectoryPoints(
        obstacle->kf_lane_tracker(curr_lane_id), sequence,
        FLAGS_prediction_duration, FLAGS_prediction_freq, &points);

    Trajectory trajectory;
    GenerateTrajectory(points, &trajectory);
    trajectory.set_probability(sequence.probability());
    trajectories_.push_back(std::move(trajectory));
  }
  ADEBUG << "Obstacle [" << obstacle->id()
         << "] has total " << trajectories_.size()
         << " trajectories.";
}

void LaneSequencePredictor::FilterLaneSequences(
    const LaneGraph& lane_graph,
    const std::string& lane_id,
    std::vector<bool> *enable_lane_sequence) {
  int num_lane_sequence = lane_graph.lane_sequence_size();
  std::vector<int> lane_change_type(num_lane_sequence, -1);
  std::pair<int, double> change(-1, -1.0);
  std::pair<int, double> all(-1, -1.0);

  // Get ADC status
  GetADC();

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    // Get lane change type
    lane_change_type[i] = GetLaneChangeType(lane_id, sequence);

    double probability = sequence.probability();

    if (::apollo::common::math::DoubleCompare(probability, all.second) > 0 ||
        (::apollo::common::math::DoubleCompare(probability, all.second) == 0 &&
         lane_change_type[i] == 0)) {
      all.first = i;
      all.second = probability;
    }
    if (lane_change_type[i] > 0 &&
        ::apollo::common::math::DoubleCompare(probability, change.second) > 0) {
      change.first = i;
      change.second = probability;
    }
  }

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    // The obstacle has interference with ADC within a small distance
    if (::apollo::common::math::DoubleCompare(
        GetLaneChangeDistanceWithADC(sequence), FLAGS_lane_change_dist) < 0) {
      (*enable_lane_sequence)[i] = false;
      continue;
    }

    double probability = sequence.probability();
    if (::apollo::common::math::DoubleCompare(
        probability, FLAGS_lane_sequence_threshold) < 0 &&
        i != all.first) {
      (*enable_lane_sequence)[i] = false;
    } else if (change.first >= 0 &&
               change.first < num_lane_sequence &&
               lane_change_type[i] > 0 &&
               lane_change_type[i] != lane_change_type[change.first]) {
      (*enable_lane_sequence)[i] = false;
    }
  }
}

void LaneSequencePredictor::GetADC() {
  ObstaclesContainer *container = dynamic_cast<ObstaclesContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PERCEPTION_OBSTACLES));
  if (container == nullptr) {
    AERROR << "Unavailable obstacle container";
    return;
  }

  Obstacle *adc = container->GetObstacle(PoseContainer::ID);
  if (adc != nullptr) {
    const Feature& feature = adc->latest_feature();
    if (feature.has_lane() &&
        feature.lane().has_lane_feature()) {
      adc_lane_id_ = feature.lane().lane_feature().lane_id();
      adc_lane_s_ = feature.lane().lane_feature().lane_s();
    }
    if (feature.has_position()) {
      adc_position_[0] = feature.position().x();
      adc_position_[1] = feature.position().y();
    }
  }
}

int LaneSequencePredictor::GetLaneChangeType(
    const std::string& lane_id,
    const LaneSequence& lane_sequence) {
  PredictionMap *map = PredictionMap::instance();

  std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
  if (lane_id == lane_change_id) {
    return 0;
  } else {
    if (map->IsLeftNeighborLane(
        map->LaneById(lane_change_id), map->LaneById(lane_id))) {
      return 1;
    } else if (map->IsRightNeighborLane(
        map->LaneById(lane_change_id), map->LaneById(lane_id))) {
      return 2;
    }
  }
  return -1;
}

double LaneSequencePredictor::GetLaneChangeDistanceWithADC(
    const LaneSequence& lane_sequence) {
  if (adc_lane_id_.empty() || lane_sequence.lane_segment_size() <= 0) {
    return std::numeric_limits<double>::max();
  }

  PredictionMap *map = PredictionMap::instance();
  std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
  double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();

  double lane_s = 0.0;
  double lane_l = 0.0;
  if (map->GetProjection(adc_position_,
                         map->LaneById(obstacle_lane_id),
                         &lane_s, &lane_l)) {
    return std::fabs(lane_s - obstacle_lane_s);
  }
  return std::numeric_limits<double>::max();
}

void LaneSequencePredictor::DrawLaneSequenceTrajectoryPoints(
    const KalmanFilter<double, 4, 2, 0>& kf,
    const LaneSequence& sequence,
    double total_time,
    double freq,
    std::vector<TrajectoryPoint> *points) {
  PredictionMap *map = PredictionMap::instance();

  Eigen::Matrix<double, 4, 1> state(kf.GetStateEstimate());
  double lane_s = state(0, 0);
  double lane_l = state(1, 0);
  double lane_speed = state(2, 0);
  double lane_acc = state(3, 0);

  Eigen::Matrix<double, 4, 4> transition(kf.GetTransitionMatrix());
  transition(0, 2) = freq;
  transition(0, 3) = 0.5 * freq * freq;
  transition(2, 3) = freq;

  int lane_segment_index = 0;
  std::string lane_id = sequence.lane_segment(lane_segment_index).lane_id();
  for (size_t i = 0; i < static_cast<size_t>(total_time / freq); ++i) {
    Eigen::Vector2d point;
    double theta = M_PI;
    if (!map->SmoothPointFromLane(lane_id, lane_s, lane_l, &point, &theta)) {
      AERROR << "Unable to get smooth point from lane [" << lane_id
             << "] with s [" << lane_s << "] and l [" << lane_l
             << "]";
      break;
    }

    if (points->size() > 0) {
      PathPoint *prev_point = points->back().mutable_path_point();
      double x_diff = point.x() - prev_point->x();
      double y_diff = point.y() - prev_point->y();
      if (::apollo::common::math::DoubleCompare(x_diff, 0.0) != 0 ||
          ::apollo::common::math::DoubleCompare(y_diff, 0.0) != 0) {
        theta = std::atan2(y_diff, x_diff);
        prev_point->set_theta(theta);
      } else {
        theta = prev_point->theta();
      }
    }

    // add trajectory point
    TrajectoryPoint trajectory_point;
    PathPoint path_point;
    path_point.set_x(point.x());
    path_point.set_y(point.y());
    path_point.set_z(0.0);
    path_point.set_theta(theta);
    trajectory_point.mutable_path_point()->CopyFrom(path_point);
    trajectory_point.set_v(lane_speed);
    trajectory_point.set_a(lane_acc);
    trajectory_point.set_relative_time(static_cast<double>(i) * freq);
    points->emplace_back(std::move(trajectory_point));

    // update state
    if (::apollo::common::math::DoubleCompare(lane_speed, 0.0) <= 0) {
      AWARN << "Non-positive lane_speed tacked : " << lane_speed;
      lane_speed = 0.0;
      lane_acc = 0.0;
      transition(1, 1) = 1.0;
    } else if (::apollo::common::math::DoubleCompare(
        lane_speed, FLAGS_max_speed) >= 0) {
      lane_speed = FLAGS_max_speed;
      lane_acc = 0.0;
    }
    state(2, 0) = lane_speed;
    state(3, 0) = lane_acc;

    state = transition * state;
    if (::apollo::common::math::DoubleCompare(lane_s, state(0, 0)) >= 0) {
      state(0, 0) = lane_s;
      state(1, 0) = lane_l;
      state(2, 0) = 0.0;
      state(3, 0) = 0.0;
      transition(1, 1) = 1.0;
    }
    lane_s = state(0, 0);
    lane_l = state(1, 0);
    lane_speed = state(2, 0);
    lane_acc = state(3, 0);

    // find next lane id
    while (lane_s > map->LaneById(lane_id)->total_length() &&
           lane_segment_index + 1 < sequence.lane_segment_size()) {
      lane_segment_index += 1;
      lane_s = lane_s - map->LaneById(lane_id)->total_length();
      state(0, 0) = lane_s;
      lane_id = sequence.lane_segment(lane_segment_index).lane_id();
    }
  }
}

std::string LaneSequencePredictor::ToString(const LaneSequence& sequence) {
  std::string str_lane_sequence = "";
  if (sequence.lane_segment_size() > 0) {
    str_lane_sequence += sequence.lane_segment(0).lane_id();
  }
  for (int i = 1; i < sequence.lane_segment_size(); ++i) {
    str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
  }
  return str_lane_sequence;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if (s.length() != t.length()) {
            return false;
        }
        vector<int> m1(256, 0);
        vector<int> m2(256, 0);
        int n = s.size();
        for (int i = 0; i < n; ++i) {
            if (m1[s[i]] != m2[t[i]]) return false;
            m1[s[i]] = i + 1;
            m2[t[i]] = i + 1;
        }
        return true;
    }
};
<commit_msg>Update isomorphic-strings.cpp<commit_after>// Time:  O(n)
// Space: O(1)

class Solution {
public:
    bool isIsomorphic(string s, string t) {
        if (s.length() != t.length()) {
            return false;
        }
        vector<int> s2t(256, 0), t2s(256, 0);
        for (int i = 0; i < s.length(); ++i) {
            if (s2t[s[i]] == 0 && t2s[t[i]] == 0) {
                s2t[s[i]] = t[i];
                t2s[t[i]] = s[i];
            } else if (s2t[s[i]] == 0 || s2t[s[i]] != t[i]) {
                // Contradict mapping.
                return false;
            }
        }
        return true;
    }
};
<|endoftext|>


<commit_before>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "future.hh"
#include "do_with.hh"
#include "future-util.hh"
#include <memory>
#include <setjmp.h>
#include <type_traits>

/// \defgroup thread-module Seastar threads
///
/// Seastar threads provide an execution environment where blocking
/// is tolerated; you can issue I/O, and wait for it in the same function,
/// rather then establishing a callback to be called with \ref future<>::then().
///
/// Seastar threads are not the same as operating system threads:
///   - seastar threads are cooperative; they are never preempted except
///     at blocking points (see below)
///   - seastar threads always run on the same core they were launched on
///
/// Like other seastar code, seastar threads may not issue blocking system calls.
///
/// A seastar thread blocking point is any function that returns a \ref future<>.
/// you block by calling \ref future<>::get(); this waits for the future to become
/// available, and in the meanwhile, other seastar threads and seastar non-threaded
/// code may execute.
///
/// Example:
/// \code
///    seastar::thread th([] {
///       sleep(5s).get();  // blocking point
///    });
/// \endcode

/// Seastar API namespace
namespace seastar {

/// \addtogroup thread-module
/// @{

class thread;

/// \cond internal
class thread_context;

namespace thread_impl {

thread_context* get();
void switch_in(thread_context* to);
void switch_out(thread_context* from);
void init();

}

extern thread_local jmp_buf g_unthreaded_context;

// Internal class holding thread state.  We can't hold this in
// \c thread itself because \c thread is movable, and we want pointers
// to this state to be captured.
class thread_context {
    static constexpr size_t _stack_size = 128*1024;
    std::unique_ptr<char[]> _stack{new char[_stack_size]};
    std::function<void ()> _func;
    jmp_buf _context;
    promise<> _done;
    bool _joined = false;
private:
    static void s_main(unsigned int lo, unsigned int hi);
    void setup();
    void main();
public:
    thread_context(std::function<void ()> func);
    void switch_in();
    void switch_out();
    friend class thread;
    friend void thread_impl::switch_in(thread_context*);
    friend void thread_impl::switch_out(thread_context*);
};

/// \endcond

/// \brief thread - stateful thread of execution
///
/// Threads allow using seastar APIs in a blocking manner,
/// by calling future::get() on a non-ready future.  When
/// this happens, the thread is put to sleep until the future
/// becomes ready.
class thread {
    std::unique_ptr<thread_context> _context;
    static thread_local thread* _current;
public:
    /// \brief Constructs a \c thread object that does not represent a thread
    /// of execution.
    thread() = default;
    /// \brief Constructs a \c thread object that represents a thread of execution
    ///
    /// \param func Callable object to execute in thread.  The callable is
    ///             called immediately.
    template <typename Func>
    thread(Func func);
    /// \brief Moves a thread object.
    thread(thread&& x) noexcept = default;
    /// \brief Move-assigns a thread object.
    thread& operator=(thread&& x) noexcept = default;
    /// \brief Destroys a \c thread object.
    ///
    /// The thread must not represent a running thread of execution (see join()).
    ~thread() { assert(!_context || _context->_joined); }
    /// \brief Waits for thread execution to terminate.
    ///
    /// Waits for thread execution to terminate, and marks the thread object as not
    /// representing a running thread of execution.
    future<> join();
};

template <typename Func>
inline
thread::thread(Func func)
        : _context(std::make_unique<thread_context>(func)) {
}

inline
future<>
thread::join() {
    _context->_joined = true;
    return _context->_done.get_future();
}

/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()).  The
/// result of the callable is returned as a future.
///
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(Func&& func, Args&&... args) {
    using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>;
    struct work {
        Func func;
        std::tuple<Args...> args;
        promise<return_type> pr;
        thread th;
    };
    return do_with(work{std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)}, [] (work& w) {
        auto ret = w.pr.get_future();
        w.th = thread([&w] {
            futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
        });
        return w.th.join().then([ret = std::move(ret)] () mutable {
            return std::move(ret);
        });
    });
}

/// @}

}
<commit_msg>thread: point out async() as an easy way to launch a thread<commit_after>/*
 * This file is open source software, licensed to you under the terms
 * of the Apache License, Version 2.0 (the "License").  See the NOTICE file
 * distributed with this work for additional information regarding copyright
 * ownership.  You may not use this file except in compliance with the License.
 *
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/*
 * Copyright (C) 2015 Cloudius Systems, Ltd.
 */

#pragma once

#include "future.hh"
#include "do_with.hh"
#include "future-util.hh"
#include <memory>
#include <setjmp.h>
#include <type_traits>

/// \defgroup thread-module Seastar threads
///
/// Seastar threads provide an execution environment where blocking
/// is tolerated; you can issue I/O, and wait for it in the same function,
/// rather then establishing a callback to be called with \ref future<>::then().
///
/// Seastar threads are not the same as operating system threads:
///   - seastar threads are cooperative; they are never preempted except
///     at blocking points (see below)
///   - seastar threads always run on the same core they were launched on
///
/// Like other seastar code, seastar threads may not issue blocking system calls.
///
/// A seastar thread blocking point is any function that returns a \ref future<>.
/// you block by calling \ref future<>::get(); this waits for the future to become
/// available, and in the meanwhile, other seastar threads and seastar non-threaded
/// code may execute.
///
/// Example:
/// \code
///    seastar::thread th([] {
///       sleep(5s).get();  // blocking point
///    });
/// \endcode
///
/// An easy way to launch a thread and carry out some computation, and return a
/// result from this execution is by using the \ref seastar::async() function.
/// The result is returned as a future, so that non-threaded code can wait for
/// the thread to terminate and yield a result.

/// Seastar API namespace
namespace seastar {

/// \addtogroup thread-module
/// @{

class thread;

/// \cond internal
class thread_context;

namespace thread_impl {

thread_context* get();
void switch_in(thread_context* to);
void switch_out(thread_context* from);
void init();

}

extern thread_local jmp_buf g_unthreaded_context;

// Internal class holding thread state.  We can't hold this in
// \c thread itself because \c thread is movable, and we want pointers
// to this state to be captured.
class thread_context {
    static constexpr size_t _stack_size = 128*1024;
    std::unique_ptr<char[]> _stack{new char[_stack_size]};
    std::function<void ()> _func;
    jmp_buf _context;
    promise<> _done;
    bool _joined = false;
private:
    static void s_main(unsigned int lo, unsigned int hi);
    void setup();
    void main();
public:
    thread_context(std::function<void ()> func);
    void switch_in();
    void switch_out();
    friend class thread;
    friend void thread_impl::switch_in(thread_context*);
    friend void thread_impl::switch_out(thread_context*);
};

/// \endcond

/// \brief thread - stateful thread of execution
///
/// Threads allow using seastar APIs in a blocking manner,
/// by calling future::get() on a non-ready future.  When
/// this happens, the thread is put to sleep until the future
/// becomes ready.
class thread {
    std::unique_ptr<thread_context> _context;
    static thread_local thread* _current;
public:
    /// \brief Constructs a \c thread object that does not represent a thread
    /// of execution.
    thread() = default;
    /// \brief Constructs a \c thread object that represents a thread of execution
    ///
    /// \param func Callable object to execute in thread.  The callable is
    ///             called immediately.
    template <typename Func>
    thread(Func func);
    /// \brief Moves a thread object.
    thread(thread&& x) noexcept = default;
    /// \brief Move-assigns a thread object.
    thread& operator=(thread&& x) noexcept = default;
    /// \brief Destroys a \c thread object.
    ///
    /// The thread must not represent a running thread of execution (see join()).
    ~thread() { assert(!_context || _context->_joined); }
    /// \brief Waits for thread execution to terminate.
    ///
    /// Waits for thread execution to terminate, and marks the thread object as not
    /// representing a running thread of execution.
    future<> join();
};

template <typename Func>
inline
thread::thread(Func func)
        : _context(std::make_unique<thread_context>(func)) {
}

inline
future<>
thread::join() {
    _context->_joined = true;
    return _context->_done.get_future();
}

/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()).  The
/// result of the callable is returned as a future.
///
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
///
/// Example:
/// \code
///    future<int> compute_sum(int a, int b) {
///        return seastar::async([a, b] {
///            // some blocking code:
///            sleep(1s).get();
///            return a + b;
///        });
///    }
/// \endcode
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(Func&& func, Args&&... args) {
    using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>;
    struct work {
        Func func;
        std::tuple<Args...> args;
        promise<return_type> pr;
        thread th;
    };
    return do_with(work{std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)}, [] (work& w) {
        auto ret = w.pr.get_future();
        w.th = thread([&w] {
            futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
        });
        return w.th.join().then([ret = std::move(ret)] () mutable {
            return std::move(ret);
        });
    });
}

/// @}

}
<|endoftext|>


<commit_before>
/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/perception/obstacle/onboard/cipv_subnode.h"

#include <vector>
#include <string>
#include <map>
#include <memory>
#include "modules/perception/obstacle/onboard/motion_service.h"
#include "modules/perception/onboard/dag_streaming.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"

namespace apollo {
namespace perception {

using apollo::common::ErrorCode;
using apollo::common::Status;

using std::vector;
using std::string;
using std::map;
// using Event;
// using EventID;
// using EventMeta;
// using IoStreamType;
// using SharedDataPtr;
// using SubnodeHelper;
// using Status;
// using StreamOutput;
// using std_msgs::String;

bool CIPVSubnode::InitInternal() {
    CHECK(shared_data_manager_ != nullptr);
    // init camera object data
    _camera_object_data = dynamic_cast<CameraObjectData*>(
        shared_data_manager_->GetSharedData("CameraObjectData"));
    if (_camera_object_data == nullptr) {
      AERROR << "Failed to get CameraObjectData.";
      return false;
    }
    // init camera object data
    _lane_shared_data = dynamic_cast<LaneSharedData*>(
        shared_data_manager_->GetSharedData("LaneSharedData"));
    if (_lane_shared_data == nullptr) {
      AERROR << "Failed to get LaneSharedData.";
      return false;
    }

    _cipv_object_data = dynamic_cast<CIPVObjectData*>(
            shared_data_manager_->GetSharedData("CIPVObjectData"));
    if (_cipv_object_data == nullptr) {
        AERROR << "Failed to get CIPVObjectData";
        return false;
    }

    AINFO << "Init shared datas successfully";

    string _reserve;
    map<string, string> reserve_field_map;
    if (!SubnodeHelper::ParseReserveField(_reserve, &reserve_field_map)) {
        AERROR << "Failed to parse reserve string: " << _reserve;
        return false;
    }

    if (!InitOutputStream(reserve_field_map)) {
        AERROR << "Failed to init output or input stream.";
        return false;
    }
    // init Cipv
    _cipv.Init();

    AINFO << "Init CIPVSubnode succ.";
    return true;
}

apollo::common::Status CIPVSubnode::ProcEvents() {
    Event event;
    if (!SubscribeEvents(&event)) {
        return Status(ErrorCode::PERCEPTION_ERROR,
                      "Failed to subscribe events.");
    }

    std::shared_ptr<SensorObjects> sensor_objs;
    if (!GetSharedData(event, &sensor_objs)) {
        return Status(ErrorCode::PERCEPTION_ERROR,
                      "Failed to get shared data.");
    }
    CipvOptions cipv_options;
    // *** To Do *** use motion manager
    // MotionService* motion_service =
    //   dynamic_cast<MotionService*>
    //     (DAGStreaming::GetSubnodeByName("MotionService"));
    // double timestamp = event.timestamp;
    // VehicleInformation vehicle_information;
    // motion_service->get_vehicle_information(timestamp,
    //                                                &vehicle_information);
    // cipv_options.yaw_angle = vehicle_information.yaw_angle;
    // cipv_options.velocity = vehicle_information.velocity;
    // cipv_options.yaw_rate = vehicle_information.yaw_rate;
    cipv_options.yaw_angle = 0.0f;  // ***** fill in the value *****
    cipv_options.velocity = 5.0f;  // ***** fill in the value *****
    cipv_options.yaw_rate = 0.0f;  // ***** fill in the value *****
    AINFO << "[CIPVSubnode] velocity " << cipv_options.velocity
              << ", yaw rate: " << cipv_options.yaw_rate
              << ", yaw angle: " << cipv_options.yaw_angle;

    // call cipv module
    if (_cipv.DetermineCipv(sensor_objs, &cipv_options)) {
      // *** To Do *** when camera_detector_subnode.cpp is included, add this
      // publish_data_and_event(event.timestamp, event.reserve,
      //                        sensor_objs, _cipv_object_data);
    }

    return Status::OK();
}

bool CIPVSubnode::InitOutputStream(const map<string, string>& fields) {
    auto camera_iter = fields.find("camera_event_id");
    if (camera_iter == fields.end()) {
       AERROR << "Failed to find camera_event_id";
       _camera_event_id = -1;
    } else {
       _camera_event_id =
         static_cast<EventID>(atoi((camera_iter->second).c_str()));
       AINFO << "camera event id is " << _camera_event_id;
    }

    auto lane_iter = fields.find("lane_event_id");
    if (lane_iter == fields.end()) {
       AERROR << "Failed to find lane_event_id";
       _lane_event_id = -1;
    } else {
       _lane_event_id =
         static_cast<EventID>(atoi((lane_iter->second).c_str()));
       AINFO << "lane event id is " << _lane_event_id;
    }

    AINFO << "Init output stream succ";
    return true;
}

bool CIPVSubnode::SubscribeEvents(Event *event) const {
    if (!event_manager_->Subscribe(_camera_event_id, event)) {
        AERROR << "Failed to subscribe event: " << _camera_event_id;
        return false;
    }
    if (!event_manager_->Subscribe(_lane_event_id, event)) {
        AERROR << "Failed to subscribe event: " << _lane_event_id;
        return false;
    }
    return true;
}

bool CIPVSubnode::GetSharedData(const Event& event,
                                std::shared_ptr<SensorObjects>* objs) const {
  double timestamp = event.timestamp;
  const string& device_id = event.reserve;
  string data_key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id,
                                              &data_key)) {
    AERROR << "Failed to produce shared data key. EventID:" << event.event_id
           << " timestamp:" << timestamp << " device_id:" << device_id;
    return false;
  }
  bool get_data_succ = false;
  // *** To DO *** uncomment
//  get_data_succ = _camera_object_data->get(data_key, objs);
//  std::shared_ptr<lane_post_process::LaneObjects> lane_objects;
//  get_data_succ = _lane_shared_data->get(data_key, &lane_objects);
//  (*objs)->lane_objects = lane_objects;

  if (!get_data_succ) {
    AERROR << "Failed to get shared data. event:" << event.to_string();
    return false;
  }
  return true;
}

REGISTER_SUBNODE(CIPVSubnode);

}  // namespace perception
}  // namespace apollo
<commit_msg>Enable CIPV using camera process subnode<commit_after>
/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/perception/obstacle/onboard/cipv_subnode.h"

#include <vector>
#include <string>
#include <map>
#include <memory>
#include "modules/perception/obstacle/onboard/motion_service.h"
#include "modules/perception/onboard/dag_streaming.h"
#include "modules/perception/onboard/event_manager.h"
#include "modules/perception/onboard/shared_data_manager.h"
#include "modules/perception/onboard/subnode_helper.h"

namespace apollo {
namespace perception {

using apollo::common::ErrorCode;
using apollo::common::Status;

using std::vector;
using std::string;
using std::map;
// using Event;
// using EventID;
// using EventMeta;
// using IoStreamType;
// using SharedDataPtr;
// using SubnodeHelper;
// using Status;
// using StreamOutput;
// using std_msgs::String;

bool CIPVSubnode::InitInternal() {
    CHECK(shared_data_manager_ != nullptr);
    // init camera object data
    _camera_object_data = dynamic_cast<CameraObjectData*>(
        shared_data_manager_->GetSharedData("CameraObjectData"));
    if (_camera_object_data == nullptr) {
      AERROR << "Failed to get CameraObjectData.";
      return false;
    }
    // init camera object data
    _lane_shared_data = dynamic_cast<LaneSharedData*>(
        shared_data_manager_->GetSharedData("LaneSharedData"));
    if (_lane_shared_data == nullptr) {
      AERROR << "Failed to get LaneSharedData.";
      return false;
    }

    _cipv_object_data = dynamic_cast<CIPVObjectData*>(
            shared_data_manager_->GetSharedData("CIPVObjectData"));
    if (_cipv_object_data == nullptr) {
        AERROR << "Failed to get CIPVObjectData";
        return false;
    }

    AINFO << "Init shared datas successfully";

    string _reserve;
    map<string, string> reserve_field_map;
    if (!SubnodeHelper::ParseReserveField(_reserve, &reserve_field_map)) {
        AERROR << "Failed to parse reserve string: " << _reserve;
        return false;
    }

    if (!InitOutputStream(reserve_field_map)) {
        AERROR << "Failed to init output or input stream.";
        return false;
    }
    // init Cipv
    _cipv.Init();

    AINFO << "Init CIPVSubnode succ.";
    return true;
}

apollo::common::Status CIPVSubnode::ProcEvents() {
    Event event;
    if (!SubscribeEvents(&event)) {
        return Status(ErrorCode::PERCEPTION_ERROR,
                      "Failed to subscribe events.");
    }

    std::shared_ptr<SensorObjects> sensor_objs;
    if (!GetSharedData(event, &sensor_objs)) {
        return Status(ErrorCode::PERCEPTION_ERROR,
                      "Failed to get shared data.");
    }
    CipvOptions cipv_options;
    // *** To Do *** use motion manager
    // MotionService* motion_service =
    //   dynamic_cast<MotionService*>
    //     (DAGStreaming::GetSubnodeByName("MotionService"));
    // double timestamp = event.timestamp;
    // VehicleInformation vehicle_information;
    // motion_service->get_vehicle_information(timestamp,
    //                                                &vehicle_information);
    // cipv_options.yaw_angle = vehicle_information.yaw_angle;
    // cipv_options.velocity = vehicle_information.velocity;
    // cipv_options.yaw_rate = vehicle_information.yaw_rate;
    cipv_options.yaw_angle = 0.0f;  // ***** fill in the value *****
    cipv_options.velocity = 5.0f;  // ***** fill in the value *****
    cipv_options.yaw_rate = 0.0f;  // ***** fill in the value *****
    AINFO << "[CIPVSubnode] velocity " << cipv_options.velocity
              << ", yaw rate: " << cipv_options.yaw_rate
              << ", yaw angle: " << cipv_options.yaw_angle;

    // call cipv module
    if (_cipv.DetermineCipv(sensor_objs, &cipv_options)) {
      // *** To Do *** when camera_detector_subnode.cpp is included, add this
      // publish_data_and_event(event.timestamp, event.reserve,
      //                        sensor_objs, _cipv_object_data);
    }

    return Status::OK();
}

bool CIPVSubnode::InitOutputStream(const map<string, string>& fields) {
    auto camera_iter = fields.find("camera_event_id");
    if (camera_iter == fields.end()) {
       AERROR << "Failed to find camera_event_id";
       _camera_event_id = -1;
    } else {
       _camera_event_id =
         static_cast<EventID>(atoi((camera_iter->second).c_str()));
       AINFO << "camera event id is " << _camera_event_id;
    }

    auto lane_iter = fields.find("lane_event_id");
    if (lane_iter == fields.end()) {
       AERROR << "Failed to find lane_event_id";
       _lane_event_id = -1;
    } else {
       _lane_event_id =
         static_cast<EventID>(atoi((lane_iter->second).c_str()));
       AINFO << "lane event id is " << _lane_event_id;
    }

    AINFO << "Init output stream succ";
    return true;
}

bool CIPVSubnode::SubscribeEvents(Event *event) const {
    if (!event_manager_->Subscribe(_camera_event_id, event)) {
        AERROR << "Failed to subscribe event: " << _camera_event_id;
        return false;
    }
    if (!event_manager_->Subscribe(_lane_event_id, event)) {
        AERROR << "Failed to subscribe event: " << _lane_event_id;
        return false;
    }
    return true;
}

bool CIPVSubnode::GetSharedData(const Event& event,
                                std::shared_ptr<SensorObjects>* objs) const {
  double timestamp = event.timestamp;
  const string& device_id = event.reserve;
  string data_key;
  if (!SubnodeHelper::ProduceSharedDataKey(timestamp, device_id,
                                              &data_key)) {
    AERROR << "Failed to produce shared data key. EventID:" << event.event_id
           << " timestamp:" << timestamp << " device_id:" << device_id;
    return false;
  }
  bool get_data_succ = false;
  // *** To DO *** uncomment
  get_data_succ = _camera_object_data->Get(data_key, objs);
  std::shared_ptr<LaneObjects> lane_objects;
  get_data_succ = _lane_shared_data->Get(data_key, &lane_objects);
  (*objs)->lane_objects = lane_objects;

  if (!get_data_succ) {
    AERROR << "Failed to get shared data. event:" << event.to_string();
    return false;
  }
  return true;
}

REGISTER_SUBNODE(CIPVSubnode);

}  // namespace perception
}  // namespace apollo
<|endoftext|>


<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "launcher.hxx"
#include "appusermodelid.hxx"

#ifndef _WINDOWS_
#   define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#   include <windows.h>
#   include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif

#include <stdlib.h>
#include <malloc.h>

#ifdef __MINGW32__
extern "C" int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
#else
extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
#endif
{
	// Set an explicit Application User Model ID for the process

	SetExplicitAppUserModelID(APPUSERMODELID);

    // Retreive startup info

    STARTUPINFO aStartupInfo;

    ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
    aStartupInfo.cb = sizeof( aStartupInfo );
    GetStartupInfo( &aStartupInfo );

    // Retrieve command line

    LPTSTR  lpCommandLine = GetCommandLine();

    {
        lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) );

        _tcscpy( lpCommandLine, GetCommandLine() );
        _tcscat( lpCommandLine, _T(" ") );
        _tcscat( lpCommandLine, APPLICATION_SWITCH );
    }

    // Calculate application name

    TCHAR   szApplicationName[MAX_PATH];
    TCHAR   szDrive[MAX_PATH];
    TCHAR   szDir[MAX_PATH];
    TCHAR   szFileName[MAX_PATH];
    TCHAR   szExt[MAX_PATH];

    GetModuleFileName( NULL, szApplicationName, MAX_PATH );
    _tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt );
    _tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") );

    PROCESS_INFORMATION aProcessInfo;

    BOOL    fSuccess = CreateProcess(
        szApplicationName,
        lpCommandLine,
        NULL,
        NULL,
        TRUE,
        0,
        NULL,
        NULL,
        &aStartupInfo,
        &aProcessInfo );

    if ( fSuccess )
    {
        // Wait for soffice process to be terminated to allow other applications
        // to wait for termination of started process

        WaitForSingleObject( aProcessInfo.hProcess, INFINITE );

        CloseHandle( aProcessInfo.hProcess );
        CloseHandle( aProcessInfo.hThread );

        return 0;
    }

    DWORD   dwError = GetLastError();

    LPVOID lpMsgBuf;

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dwError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPTSTR)&lpMsgBuf,
        0,
        NULL
    );

    // Display the string.
    MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR );

    // Free the buffer.
    LocalFree( lpMsgBuf );

    return GetLastError();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>Don't spam fellow developers until I fix the problem in MinGW<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2000, 2010 Oracle and/or its affiliates.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#include "launcher.hxx"
#include "appusermodelid.hxx"

#ifndef _WINDOWS_
#   define WIN32_LEAN_AND_MEAN
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#   include <windows.h>
#   include <shellapi.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif

#include <stdlib.h>
#include <malloc.h>

#ifdef __MINGW32__
extern "C" int APIENTRY WinMain( HINSTANCE, HINSTANCE, LPSTR, int )
#else
extern "C" int APIENTRY _tWinMain( HINSTANCE, HINSTANCE, LPTSTR, int )
#endif
{
	// Set an explicit Application User Model ID for the process

    // FIXME: Comment this out until I find a fix for minGW.
    // SetExplicitAppUserModelID(APPUSERMODELID);

    // Retreive startup info

    STARTUPINFO aStartupInfo;

    ZeroMemory( &aStartupInfo, sizeof(aStartupInfo) );
    aStartupInfo.cb = sizeof( aStartupInfo );
    GetStartupInfo( &aStartupInfo );

    // Retrieve command line

    LPTSTR  lpCommandLine = GetCommandLine();

    {
        lpCommandLine = (LPTSTR)_alloca( sizeof(_TCHAR) * (_tcslen(lpCommandLine) + _tcslen(APPLICATION_SWITCH) + 2) );

        _tcscpy( lpCommandLine, GetCommandLine() );
        _tcscat( lpCommandLine, _T(" ") );
        _tcscat( lpCommandLine, APPLICATION_SWITCH );
    }

    // Calculate application name

    TCHAR   szApplicationName[MAX_PATH];
    TCHAR   szDrive[MAX_PATH];
    TCHAR   szDir[MAX_PATH];
    TCHAR   szFileName[MAX_PATH];
    TCHAR   szExt[MAX_PATH];

    GetModuleFileName( NULL, szApplicationName, MAX_PATH );
    _tsplitpath( szApplicationName, szDrive, szDir, szFileName, szExt );
    _tmakepath( szApplicationName, szDrive, szDir, OFFICE_IMAGE_NAME, _T(".exe") );

    PROCESS_INFORMATION aProcessInfo;

    BOOL    fSuccess = CreateProcess(
        szApplicationName,
        lpCommandLine,
        NULL,
        NULL,
        TRUE,
        0,
        NULL,
        NULL,
        &aStartupInfo,
        &aProcessInfo );

    if ( fSuccess )
    {
        // Wait for soffice process to be terminated to allow other applications
        // to wait for termination of started process

        WaitForSingleObject( aProcessInfo.hProcess, INFINITE );

        CloseHandle( aProcessInfo.hProcess );
        CloseHandle( aProcessInfo.hThread );

        return 0;
    }

    DWORD   dwError = GetLastError();

    LPVOID lpMsgBuf;

    FormatMessage(
        FORMAT_MESSAGE_ALLOCATE_BUFFER |
        FORMAT_MESSAGE_FROM_SYSTEM,
        NULL,
        dwError,
        MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
        (LPTSTR)&lpMsgBuf,
        0,
        NULL
    );

    // Display the string.
    MessageBox( NULL, (LPCTSTR)lpMsgBuf, NULL, MB_OK | MB_ICONERROR );

    // Free the buffer.
    LocalFree( lpMsgBuf );

    return GetLastError();
}

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 6/14/2020, 2:15:35 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Solve -----

constexpr int D{12};
constexpr int M{100010};

struct Info
{
  int value, weight;
};

Info operator+(Info const &l, Info const &r)
{
  return Info{l.value + r.value, l.weight + r.weight};
}

class Solve
{
  int N, Q;
  vector<int> V, W;
  vector<int> X, L;
  vector<vector<int>> DP;

public:
  Solve() : V(1), W(1), X{}, L{}, DP(1 << D)
  {
    cin >> N;
    for (auto i{0}; i < N; ++i)
    {
      int x, y;
      cin >> x >> y;
      V.push_back(x);
      W.push_back(y);
    }
    cin >> Q;
    for (auto i{0}; i < Q; ++i)
    {
      int x, y;
      cin >> x >> y;
      X.push_back(x);
      L.push_back(y);
    }
  }

  void flush()
  {
    for (auto i{0}; i < min(N, 1 << D); ++i)
    {
      DP[i] = make_knapsack(i);
    }
    for (auto i{0}; i < Q; ++i)
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "X[" << i << "] = " << X[i] << endl;
      cerr << "L[" << i << "] = " << L[i] << endl;
#endif
      cout << calc_ans(X[i], L[i]) << endl;
    }
  }

private:
  int calc_ans(int v, int l)
  {
    vector<Info> T{Info{0, 0}};
    while (v >= 1 << D)
    {
      vector<Info> U;
      Info tmp{V[v], W[v]};
      for (auto const &e : T)
      {
        U.push_back(tmp + e);
      }
      copy(U.begin(), U.end(), back_inserter(T));
      v >>= 1;
    }
    int ans{0};
    for (auto const &e : T)
    {
      if (e.weight > l)
      {
        continue;
      }
      ch_max(ans, DP[v][l - e.weight] + e.value);
    }
    return ans;
  }

  vector<int> make_knapsack(int v)
  {
    vector<int> dp(M, 0);
    while (v > 0)
    {
      for (auto i{M - 1}; i >= 0; --i)
      {
        if (int t{i + W[v]}; t < M)
        {
          ch_max(dp[t], dp[i] + V[v]);
        }
      }
      v >>= 1;
    }
    return dp;
  }
};

// ----- main() -----

int main()
{
  Solve solve;
  solve.flush();
}
<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 6/14/2020, 2:15:35 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Solve -----

constexpr int D{12};
constexpr int M{100010};

struct Info
{
  int value, weight;
};

Info operator+(Info const &l, Info const &r)
{
  return Info{l.value + r.value, l.weight + r.weight};
}

class Solve
{
  int N, Q;
  vector<int> V, W;
  vector<int> X, L;
  vector<vector<int>> DP;

public:
  Solve() : V(1), W(1), X{}, L{}, DP(1 << D)
  {
    cin >> N;
    for (auto i{0}; i < N; ++i)
    {
      int x, y;
      cin >> x >> y;
      V.push_back(x);
      W.push_back(y);
    }
    cin >> Q;
    for (auto i{0}; i < Q; ++i)
    {
      int x, y;
      cin >> x >> y;
      X.push_back(x);
      L.push_back(y);
    }
  }

  void flush()
  {
    for (auto i{0}; i < min(N, 1 << D); ++i)
    {
      DP[i] = make_knapsack(i);
    }
    for (auto i{0}; i < Q; ++i)
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "X[" << i << "] = " << X[i] << endl;
      cerr << "L[" << i << "] = " << L[i] << endl;
#endif
      cout << calc_ans(X[i], L[i]) << endl;
    }
  }

private:
  int calc_ans(int v, int l)
  {
    vector<Info> T{Info{0, 0}};
    while (v >= 1 << D)
    {
      vector<Info> U;
      Info tmp{V[v], W[v]};
      for (auto const &e : T)
      {
        U.push_back(tmp + e);
      }
      copy(U.begin(), U.end(), back_inserter(T));
      v >>= 1;
    }
    int ans{0};
    for (auto const &e : T)
    {
      if (e.weight > l)
      {
        continue;
      }
      ch_max(ans, DP[v][l - e.weight] + e.value);
    }
#if DEBUG == 1
    cerr << "Here" << endl;
#endif
    return ans;
  }

  vector<int> make_knapsack(int v)
  {
    vector<int> dp(M, 0);
    while (v > 0)
    {
      for (auto i{M - 1}; i >= 0; --i)
      {
        if (int t{i + W[v]}; t < M)
        {
          ch_max(dp[t], dp[i] + V[v]);
        }
      }
      v >>= 1;
    }
    return dp;
  }
};

// ----- main() -----

int main()
{
  Solve solve;
  solve.flush();
}
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 6/14/2020, 2:15:35 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Solve -----

constexpr int D{12};
constexpr int M{100010};

struct Info
{
  int value, weight;
};

Info operator+(Info const &l, Info const &r)
{
  return Info{l.value + r.value, l.weight + r.weight};
}

class Solve
{
  int N, Q;
  vector<int> V, W;
  vector<int> X, L;
  vector<vector<int>> DP;

public:
  Solve() : V(1), W(1), X{}, L{}, DP(1 << D)
  {
    cin >> N;
    for (auto i{0}; i < N; ++i)
    {
      int x, y;
      cin >> x >> y;
      V.push_back(x);
      W.push_back(y);
    }
    cin >> Q;
    for (auto i{0}; i < Q; ++i)
    {
      int x, y;
      cin >> x >> y;
      X.push_back(x);
      L.push_back(y);
    }
  }

  void flush()
  {
    for (auto i{0}; i < min(N, 1 << D); ++i)
    {
      DP[i] = make_knapsack(i);
    }
    for (auto i{0}; i < Q; ++i)
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "X[" << i << "] = " << X[i] << endl;
      cerr << "L[" << i << "] = " << L[i] << endl;
#endif
      cout << calc_ans(X[i], L[i]) << endl;
    }
  }

private:
  int calc_ans(int v, int l)
  {
    vector<Info> T{Info{0, 0}};
    while (v >= 1 << D)
    {
      vector<Info> U;
      Info tmp{V[v], W[v]};
      for (auto const &e : T)
      {
        U.push_back(tmp + e);
      }
      copy(U.begin(), U.end(), back_inserter(T));
      v >>= 1;
    }
#if DEBUG == 1
    cerr << "Here" << endl;
#endif
    int ans{0};
    for (auto const &e : T)
    {
      if (e.weight > l)
      {
        continue;
      }
      ch_max(ans, DP[v][l - e.weight] + e.value);
    }
    return ans;
  }

  vector<int> make_knapsack(int v)
  {
    vector<int> dp(M, 0);
    while (v > 0)
    {
      for (auto i{M - 1}; i >= 0; --i)
      {
        if (int t{i + W[v]}; t < M)
        {
          ch_max(dp[t], dp[i] + V[v]);
        }
      }
      v >>= 1;
    }
    return dp;
  }
};

// ----- main() -----

int main()
{
  Solve solve;
  solve.flush();
}
<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 6/14/2020, 2:15:35 AM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
using ld = long double;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1'000'000'007LL};
// constexpr ll MOD{998'244'353LL}; // be careful
constexpr ll MAX_SIZE{3'000'010LL};
// constexpr ll MAX_SIZE{30'000'010LL}; // if 10^7 is needed
// ----- ch_max and ch_min -----
template <typename T>
void ch_max(T &left, T right)
{
  if (left < right)
  {
    left = right;
  }
}
template <typename T>
void ch_min(T &left, T right)
{
  if (left > right)
  {
    left = right;
  }
}
// ----- Mint -----
template <ll MOD = MOD>
class Mint
{
public:
  ll x;
  Mint() : x{0LL} {}
  Mint(ll x) : x{(x % MOD + MOD) % MOD} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(Mint const &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(Mint const &a) { return *this += -a; }
  Mint &operator++() { return *this += 1; }
  Mint operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(Mint const &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(Mint const &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(Mint const &a) const { return Mint(*this) += a; }
  Mint operator-(Mint const &a) const { return Mint(*this) -= a; }
  Mint operator*(Mint const &a) const { return Mint(*this) *= a; }
  Mint operator/(Mint const &a) const { return Mint(*this) /= a; }
  bool operator<(Mint const &a) const { return x < a.x; }
  bool operator<=(Mint const &a) const { return x <= a.x; }
  bool operator>(Mint const &a) const { return x > a.x; }
  bool operator>=(Mint const &a) const { return x >= a.x; }
  bool operator==(Mint const &a) const { return x == a.x; }
  bool operator!=(Mint const &a) const { return !(*this == a); }
  Mint power(ll N) const
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      Mint half = power(N / 2);
      return half * half;
    }
  }
};
template <ll MOD>
Mint<MOD> operator+(ll lhs, Mint<MOD> const &rhs) { return rhs + lhs; }
template <ll MOD>
Mint<MOD> operator-(ll lhs, Mint<MOD> const &rhs) { return -rhs + lhs; }
template <ll MOD>
Mint<MOD> operator*(ll lhs, Mint<MOD> const &rhs) { return rhs * lhs; }
template <ll MOD>
Mint<MOD> operator/(ll lhs, Mint<MOD> const &rhs) { return Mint<MOD>{lhs} / rhs; }
template <ll MOD>
istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; }
template <ll MOD>
ostream &operator<<(ostream &stream, Mint<MOD> const &a) { return stream << a.x; }
// ----- Combination -----
template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE>
class Combination
{
public:
  vector<Mint<MOD>> inv, fact, factinv;
  Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i{2LL}; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[MOD % i]) * (MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i{1LL}; i < MAX_SIZE; i++)
    {
      fact[i] = Mint<MOD>(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  Mint<MOD> operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
  Mint<MOD> catalan(int x, int y)
  {
    return (*this)(x + y, y) - (*this)(x + y, y - 1);
  }
};
// ----- for C++14 -----
using mint = Mint<MOD>;
using combination = Combination<MOD, MAX_SIZE>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- Infty -----
template <typename T>
constexpr T Infty() { return numeric_limits<T>::max(); }
template <typename T>
constexpr T mInfty() { return numeric_limits<T>::min(); }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1'000'000'000'000'010LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Solve -----

constexpr int D{12};
constexpr int M{100010};

struct Info
{
  int value, weight;
};

Info operator+(Info const &l, Info const &r)
{
  return Info{l.value + r.value, l.weight + r.weight};
}

class Solve
{
  int N, Q;
  vector<int> V, W;
  vector<int> X, L;
  vector<vector<int>> DP;

public:
  Solve() : V(1), W(1), X{}, L{}, DP(1 << D)
  {
    cin >> N;
    for (auto i{0}; i < N; ++i)
    {
      int x, y;
      cin >> x >> y;
      V.push_back(x);
      W.push_back(y);
    }
    cin >> Q;
    for (auto i{0}; i < Q; ++i)
    {
      int x, y;
      cin >> x >> y;
      X.push_back(x);
      L.push_back(y);
    }
  }

  void flush()
  {
    for (auto i{0}; i < min(N, 1 << D); ++i)
    {
      DP[i] = make_knapsack(i);
    }
    for (auto i{0}; i < Q; ++i)
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "X[" << i << "] = " << X[i] << endl;
      cerr << "L[" << i << "] = " << L[i] << endl;
#endif
      cout << calc_ans(X[i], L[i]) << endl;
    }
  }

private:
  int calc_ans(int v, int l)
  {
    vector<Info> T{Info{0, 0}};
    while (v >= 1 << D)
    {
      vector<Info> U;
      Info tmp{V[v], W[v]};
      for (auto const &e : T)
      {
        U.push_back(tmp + e);
      }
      copy(U.begin(), U.end(), back_inserter(T));
      v >>= 1;
    }
    int ans{0};
    for (auto const &e : T)
    {
      if (e.weight > l)
      {
        continue;
      }
#if DEBUG == 1
      cerr << "e.weight = " << e.weight << endl;
      cerr << "e.value = " << e.value << endl;
#endif
      ch_max(ans, DP[v][l - e.weight] + e.value);
    }
    return ans;
  }

  vector<int> make_knapsack(int v)
  {
    vector<int> dp(M, 0);
    while (v > 0)
    {
      for (auto i{M - 1}; i >= 0; --i)
      {
        if (int t{i + W[v]}; t < M)
        {
          ch_max(dp[t], dp[i] + V[v]);
        }
      }
      v >>= 1;
    }
    return dp;
  }
};

// ----- main() -----

int main()
{
  Solve solve;
  solve.flush();
}
<|endoftext|>