<commit_before>/**
 * @file scene.cpp
 * @brief Function definitions for scenes.
 *
 * @author Eric Butler (edbutler)
 * @author Kristin Siu (kasiu)
 * @author Justin Gallagher (jrgallag)
 */

#include "scene/scene.hpp"

namespace _462 {

Geometry::Geometry():
    position(Vector3::Zero()),
    orientation(Quaternion::Identity()),
    scale(Vector3::Ones())
{

}

Geometry::~Geometry() { }

bool Geometry::initialize()
{
    make_inverse_transformation_matrix(&invMat, position, orientation, scale);
    make_transformation_matrix(&mat, position, orientation, scale);
    make_normal_matrix(&normMat, mat);
    return true;
}

SphereLight::SphereLight():
    position(Vector3::Zero()),
    color(Color3::White()),
    radius(real_t(0))
{
    attenuation.constant = 1;
    attenuation.linear = 0;
    attenuation.quadratic = 0;
}

/**
 * @brief Calculates whether this ray intersects the light, and at what time.
 * @param ray: Ray to test.
 * @param t: Where the time to intersection will be returned.
 * @return: bool
 */
bool SphereLight::intersect(const Ray& ray, real_t &t) {
    // Calculate quadratic coefficients
    real_t a = dot(ray.d, ray.d);
    real_t b = 2.0 * dot(ray.d, ray.e - position);
    real_t c = dot(ray.e - position, ray.e - position) - radius * radius;

    // Get t
    t = solve_time(a, b, c);

    return t >= EPS;
}

/**
 * @brief Samples the light to determine its contribution to a point.
 * @param pos: Position of intersection
 * @param wnorm: Surface normal at intersection
 * @param scene: Scene to sample
 * @return: Color of the light, sampled on random points on the light surface
 */
Color3 SphereLight::sample(Vector3 &pos, Vector3 &wnorm, Scene &scene) {
    Color3 cumulative = Color3(0.0, 0.0, 0.0);
    for (int i = 0; i < DIRECT_SAMPLE_COUNT; i++) {
        Vector3 rand_pos = normalize(Vector3(random_gaussian(),
                    random_gaussian(), random_gaussian()));
        rand_pos = rand_pos * radius + position;
        Ray new_ray = Ray(pos, normalize(rand_pos - pos));

        real_t time = length(rand_pos - pos);

        Intersection result = scene.cast_ray(new_ray);

        if (result.time < EPS || time < result.time) {

            real_t atten = 1.0 / (attenuation.constant + time *
                    attenuation.linear + time * time * attenuation.quadratic);
            real_t scale = dot(new_ray.d, wnorm);

            if (scale > 0) {
                cumulative += scale * atten * color *
                    (1.0 / DIRECT_SAMPLE_COUNT);
            }
        }
    }

    return cumulative;
}

Scene::Scene()
{
    reset();
}

Scene::~Scene()
{
    reset();
}

bool Scene::initialize()
{
    bool res = true;

    for (unsigned int i = 0; i < num_geometries(); i++)
        res &= geometries[i]->initialize();

    intersections = 0;

    if (triangles.size() > 0) {
        return res;
    }

    for (unsigned int i = 0; i < num_geometries(); i++) {
        TriangleList newtris = geometries[i]->get_triangles();
        triangles.insert(triangles.end(), newtris.begin(), newtris.end());
    }

    if (fpga_accel) {
        size_t rounded_tris = triangles.size() + PARALLEL_TESTS
            - 1 - (triangles.size() - 1) % PARALLEL_TESTS;
        std::cout << rounded_tris << std::endl;
        axidma_interface =
            new AxiDma(rounded_tris * 15 * sizeof(float), rounded_tris
                    * 3 * sizeof(float));
    }

    return res;
}

Geometry* const* Scene::get_geometries() const
{
    return geometries.empty() ? NULL : &geometries[0];
}

size_t Scene::num_geometries() const
{
    return geometries.size();
}

const SphereLight* Scene::get_lights() const
{
    return point_lights.empty() ? NULL : &point_lights[0];
}

size_t Scene::num_lights() const
{
    return point_lights.size();
}

Material* const* Scene::get_materials() const
{
    return materials.empty() ? NULL : &materials[0];
}

size_t Scene::num_materials() const
{
    return materials.size();
}

Mesh* const* Scene::get_meshes() const
{
    return meshes.empty() ? NULL : &meshes[0];
}

size_t Scene::num_meshes() const
{
    return meshes.size();
}

/**
 * @brief Find the color of the point of intersection between a ray and the
 *        scene.
 * @param ray: Ray to send.
 * @param refracti: Refractive index of ray medium.
 * @param depth: Number of recursive calls made.
 * @return: Color of the point of intersection.
 */
Color3 Scene::trace_ray(Ray &ray, int refracti, int depth) {
    // Abort if too deep
    if (depth > MAX_DEPTH) return Color3(0.0, 0.0, 0.0);

    // Use ray casting to find if an object is seen
    Intersection intersect = cast_ray(ray);

    // Calculate color
    if (intersect.time >= EPS) {
        return intersect.shape->color(intersect, ray, *this, depth, refracti);
    } else {
        return background_color;
    }
}

/**
 * @brief Casts a ray through the scene, returning information about the nearest
 *        intersection, if one occurs.
 * @param ray: Ray to cast.
 * @return: Intersection object representing the intersection.
 */
Intersection Scene::cast_ray(Ray &ray) {

    // Use ray casting to find if an object is seen
    Intersection min_inter;
    min_inter.time = -1.0;

    if (simd_accel) {
        // Use SIMD accelerated triangle intersections
        min_inter = SimpleTriangle::simd_intersect(triangles, ray);
    } else if (fpga_accel) {
        min_inter = SimpleTriangle::fpga_intersect(triangles, ray,
                axidma_interface);
    } else {
        // Use normal CPU triangle intersections
        for (unsigned int i = 0; i < triangles.size(); i++) {
            real_t temp_beta, temp_gamma, temp_t;

            temp_t = triangles[i]->intersect(ray, temp_beta, temp_gamma);

            if (temp_t != -1 && temp_t >= EPS &&
                    (min_inter.time < EPS || temp_t < min_inter.time)) {

                min_inter.time = temp_t;
                min_inter.x = temp_beta;
                min_inter.y = temp_gamma;
                min_inter.shape = triangles[i]->parent;
                min_inter.tri = triangles[i]->num_tri;
            }
        }
    }

    long long num_tris = (long long) triangles.size();

    #pragma omp atomic
    intersections += num_tris;

    return min_inter;
}

void Scene::reset()
{
    for ( TriangleList::iterator i = triangles.begin(); i != triangles.end(); ++i ) {
        delete *i;
    }
    for ( GeometryList::iterator i = geometries.begin(); i != geometries.end(); ++i ) {
        delete *i;
    }
    for ( MaterialList::iterator i = materials.begin(); i != materials.end(); ++i ) {
        delete *i;
    }
    for ( MeshList::iterator i = meshes.begin(); i != meshes.end(); ++i ) {
        delete *i;
    }

    geometries.clear();
    materials.clear();
    meshes.clear();
    point_lights.clear();

    camera = Camera();

    background_color = Color3::Black();
    ambient_light = Color3::Black();
    refractive_index = 1.0;
}

void Scene::add_geometry( Geometry* g )
{
    geometries.push_back( g );
}

void Scene::add_material( Material* m )
{
    materials.push_back( m );
}

void Scene::add_mesh( Mesh* m )
{
    meshes.push_back( m );
}

void Scene::add_light( const SphereLight& l )
{
    point_lights.push_back( l );
}

} /* _462 */

<commit_msg>Print number of triangles to be tested<commit_after>/**
 * @file scene.cpp
 * @brief Function definitions for scenes.
 *
 * @author Eric Butler (edbutler)
 * @author Kristin Siu (kasiu)
 * @author Justin Gallagher (jrgallag)
 */

#include "scene/scene.hpp"

namespace _462 {

Geometry::Geometry():
    position(Vector3::Zero()),
    orientation(Quaternion::Identity()),
    scale(Vector3::Ones())
{

}

Geometry::~Geometry() { }

bool Geometry::initialize()
{
    make_inverse_transformation_matrix(&invMat, position, orientation, scale);
    make_transformation_matrix(&mat, position, orientation, scale);
    make_normal_matrix(&normMat, mat);
    return true;
}

SphereLight::SphereLight():
    position(Vector3::Zero()),
    color(Color3::White()),
    radius(real_t(0))
{
    attenuation.constant = 1;
    attenuation.linear = 0;
    attenuation.quadratic = 0;
}

/**
 * @brief Calculates whether this ray intersects the light, and at what time.
 * @param ray: Ray to test.
 * @param t: Where the time to intersection will be returned.
 * @return: bool
 */
bool SphereLight::intersect(const Ray& ray, real_t &t) {
    // Calculate quadratic coefficients
    real_t a = dot(ray.d, ray.d);
    real_t b = 2.0 * dot(ray.d, ray.e - position);
    real_t c = dot(ray.e - position, ray.e - position) - radius * radius;

    // Get t
    t = solve_time(a, b, c);

    return t >= EPS;
}

/**
 * @brief Samples the light to determine its contribution to a point.
 * @param pos: Position of intersection
 * @param wnorm: Surface normal at intersection
 * @param scene: Scene to sample
 * @return: Color of the light, sampled on random points on the light surface
 */
Color3 SphereLight::sample(Vector3 &pos, Vector3 &wnorm, Scene &scene) {
    Color3 cumulative = Color3(0.0, 0.0, 0.0);
    for (int i = 0; i < DIRECT_SAMPLE_COUNT; i++) {
        Vector3 rand_pos = normalize(Vector3(random_gaussian(),
                    random_gaussian(), random_gaussian()));
        rand_pos = rand_pos * radius + position;
        Ray new_ray = Ray(pos, normalize(rand_pos - pos));

        real_t time = length(rand_pos - pos);

        Intersection result = scene.cast_ray(new_ray);

        if (result.time < EPS || time < result.time) {

            real_t atten = 1.0 / (attenuation.constant + time *
                    attenuation.linear + time * time * attenuation.quadratic);
            real_t scale = dot(new_ray.d, wnorm);

            if (scale > 0) {
                cumulative += scale * atten * color *
                    (1.0 / DIRECT_SAMPLE_COUNT);
            }
        }
    }

    return cumulative;
}

Scene::Scene()
{
    reset();
}

Scene::~Scene()
{
    reset();
}

bool Scene::initialize()
{
    bool res = true;

    for (unsigned int i = 0; i < num_geometries(); i++)
        res &= geometries[i]->initialize();

    intersections = 0;

    if (triangles.size() > 0) {
        return res;
    }

    for (unsigned int i = 0; i < num_geometries(); i++) {
        TriangleList newtris = geometries[i]->get_triangles();
        triangles.insert(triangles.end(), newtris.begin(), newtris.end());
    }

    std::cout << triangles.size() << " triangles" << std::endl;

    if (fpga_accel) {
        size_t rounded_tris = triangles.size() + PARALLEL_TESTS
            - 1 - (triangles.size() - 1) % PARALLEL_TESTS;
        axidma_interface =
            new AxiDma(rounded_tris * 15 * sizeof(float), rounded_tris
                    * 3 * sizeof(float));
    }

    return res;
}

Geometry* const* Scene::get_geometries() const
{
    return geometries.empty() ? NULL : &geometries[0];
}

size_t Scene::num_geometries() const
{
    return geometries.size();
}

const SphereLight* Scene::get_lights() const
{
    return point_lights.empty() ? NULL : &point_lights[0];
}

size_t Scene::num_lights() const
{
    return point_lights.size();
}

Material* const* Scene::get_materials() const
{
    return materials.empty() ? NULL : &materials[0];
}

size_t Scene::num_materials() const
{
    return materials.size();
}

Mesh* const* Scene::get_meshes() const
{
    return meshes.empty() ? NULL : &meshes[0];
}

size_t Scene::num_meshes() const
{
    return meshes.size();
}

/**
 * @brief Find the color of the point of intersection between a ray and the
 *        scene.
 * @param ray: Ray to send.
 * @param refracti: Refractive index of ray medium.
 * @param depth: Number of recursive calls made.
 * @return: Color of the point of intersection.
 */
Color3 Scene::trace_ray(Ray &ray, int refracti, int depth) {
    // Abort if too deep
    if (depth > MAX_DEPTH) return Color3(0.0, 0.0, 0.0);

    // Use ray casting to find if an object is seen
    Intersection intersect = cast_ray(ray);

    // Calculate color
    if (intersect.time >= EPS) {
        return intersect.shape->color(intersect, ray, *this, depth, refracti);
    } else {
        return background_color;
    }
}

/**
 * @brief Casts a ray through the scene, returning information about the nearest
 *        intersection, if one occurs.
 * @param ray: Ray to cast.
 * @return: Intersection object representing the intersection.
 */
Intersection Scene::cast_ray(Ray &ray) {

    // Use ray casting to find if an object is seen
    Intersection min_inter;
    min_inter.time = -1.0;

    if (simd_accel) {
        // Use SIMD accelerated triangle intersections
        min_inter = SimpleTriangle::simd_intersect(triangles, ray);
    } else if (fpga_accel) {
        min_inter = SimpleTriangle::fpga_intersect(triangles, ray,
                axidma_interface);
    } else {
        // Use normal CPU triangle intersections
        for (unsigned int i = 0; i < triangles.size(); i++) {
            real_t temp_beta, temp_gamma, temp_t;

            temp_t = triangles[i]->intersect(ray, temp_beta, temp_gamma);

            if (temp_t != -1 && temp_t >= EPS &&
                    (min_inter.time < EPS || temp_t < min_inter.time)) {

                min_inter.time = temp_t;
                min_inter.x = temp_beta;
                min_inter.y = temp_gamma;
                min_inter.shape = triangles[i]->parent;
                min_inter.tri = triangles[i]->num_tri;
            }
        }
    }

    long long num_tris = (long long) triangles.size();

    #pragma omp atomic
    intersections += num_tris;

    return min_inter;
}

void Scene::reset()
{
    for ( TriangleList::iterator i = triangles.begin(); i != triangles.end(); ++i ) {
        delete *i;
    }
    for ( GeometryList::iterator i = geometries.begin(); i != geometries.end(); ++i ) {
        delete *i;
    }
    for ( MaterialList::iterator i = materials.begin(); i != materials.end(); ++i ) {
        delete *i;
    }
    for ( MeshList::iterator i = meshes.begin(); i != meshes.end(); ++i ) {
        delete *i;
    }

    geometries.clear();
    materials.clear();
    meshes.clear();
    point_lights.clear();

    camera = Camera();

    background_color = Color3::Black();
    ambient_light = Color3::Black();
    refractive_index = 1.0;
}

void Scene::add_geometry( Geometry* g )
{
    geometries.push_back( g );
}

void Scene::add_material( Material* m )
{
    materials.push_back( m );
}

void Scene::add_mesh( Mesh* m )
{
    meshes.push_back( m );
}

void Scene::add_light( const SphereLight& l )
{
    point_lights.push_back( l );
}

} /* _462 */

<|endoftext|>


<commit_before>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY vincent.acary@inrialpes.fr
 */
/*! \file PivotJoint.cpp

*/

#include "PivotJoint.hpp"
#include <boost/math/quaternion.hpp>

int PivotJointR::_sNbEqualities = 5;

PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2, SP::SimpleVector P, SP::SimpleVector A): KneeJointR(d1, d2, P)
{
  SP::SiconosVector q1 = d1->q0();
  ::boost::math::quaternion<float>    quat1(q1->getValue(3), q1->getValue(4), q1->getValue(5), q1->getValue(6));
  ::boost::math::quaternion<float>    quatA(0, A->getValue(0), A->getValue(1), A->getValue(2));
  ::boost::math::quaternion<float>    quatBuff(0, 0, 0, 0);
  /*calcul of axis _A*/
  quatBuff = quat1 * quatA / quat1;
  _Ax = quatBuff.R_component_2();
  _Ay = quatBuff.R_component_3();
  _Az = quatBuff.R_component_4();
  buildA1A2();
}
/* constructor,
   \param a SP::NewtonEulerDS d1, a dynamical system containing the intial position
   \param a SP::SimpleVector P0, P0 contains the coordinates of the Pivot point, in the absolute frame.
*/
PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::SimpleVector P0, SP::SimpleVector A): KneeJointR(d1, P0)
{

  _Ax = A->getValue(0);
  _Ay = A->getValue(1);
  _Az = A->getValue(2);
  buildA1A2();
}
void PivotJointR::buildA1A2()
{
  double normA = sqrt(_Ax * _Ax + _Ay * _Ay + _Az * _Az);
  assert(normA > 0.9 && "PivotJoint, normA to small\n");
  _Ax /= normA;
  _Ay /= normA;
  _Az /= normA;
  std::cout << "JointKnee: _Ax _Ay _Az :" << _Ax << " " << _Ay << " " << _Az << std::endl;
  /*build _A1*/
  if (_Ax > _Ay)
  {
    if (_Ax > _Az) /*_Ax is the bigest*/
    {
      _A1x = _Ay;
      _A1y = -_Ax;
      _A1z = 0;
      _A2x = _Az;
      _A2z = -_Ax;
      _A2y = 0;
    }
    else  /*_Az is the biggest*/
    {
      _A1z = _Ax;
      _A1y = -_Az;
      _A1x = 0;
      _A2z = _Ay;
      _A2x = -_Az;
      _A2y = 0;
    }
  }
  else if (_Ay > _Az)  /*_Ay is the bigest*/
  {
    _A1y = _Ax;
    _A1x = -_Ay;
    _A1z = 0;
    _A2y = _Az;
    _A2z = -_Ay;
    _A2x = 0;
  }
  else  /*_Az is the biggest*/
  {
    _A1z = _Ax;
    _A1y = -_Az;
    _A1x = 0;
    _A2z = _Ay;
    _A2x = -_Az;
    _A2y = 0;
  }
  assert(fabs(_A1x * _Ax + _A1y * _Ay + _A1z * _Az) < 1e-9 && "PivotJoint, _A1 wrong\n");
  assert(fabs(_A2x * _Ax + _A2y * _Ay + _A2z * _Az) < 1e-9 && "PivotJoint, _A2 wrong\n");
  assert(fabs(_A1x * _A2x + _A1y * _A2y + _A1z * _A2z) < 1e-9 && "PivotJoint, _A12 wrong\n");
  std::cout << "JointPivot: _A1x _A1y _A1z :" << _A1x << " " << _A1y << " " << _A1z << std::endl;
  std::cout << "JointPivot: _A2x _A2y _A2z :" << _A2x << " " << _A2y << " " << _A2z << std::endl;
}
void PivotJointR::Jd1d2(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13, double X2, double Y2, double Z2, double q20, double q21, double q22, double q23)
{
  KneeJointR::Jd1d2(X1, Y1, Z1, q10, q11, q12, q13, X2, Y2, Z2, q20, q21, q22, q23);

  _jachq->setValue(3, 0, 0);
  _jachq->setValue(3, 1, 0);
  _jachq->setValue(3, 2, 0);
  _jachq->setValue(3, 3, _A1x * (-q21) + _A1y * (-q22) + _A1z * (-q23));
  _jachq->setValue(3, 4, _A1x * (q20) + _A1y * (q23) + _A1z * (-q22));
  _jachq->setValue(3, 5, _A1x * (-q23) + _A1y * (q20) + _A1z * (q21));
  _jachq->setValue(3, 6, _A1x * (q22) + _A1y * (-q21) + _A1z * (q20));
  _jachq->setValue(3, 7, 0);
  _jachq->setValue(3, 8, 0);
  _jachq->setValue(3, 9, 0);
  _jachq->setValue(3, 10, _A1x * (q11) + _A1y * (q12) + _A1z * (q13));
  _jachq->setValue(3, 11, _A1x * (-q10) + _A1y * (-q13) + _A1z * (q12));
  _jachq->setValue(3, 12, _A1x * (q13) + _A1y * (-q10) + _A1z * (-q11));
  _jachq->setValue(3, 13, _A1x * (-q12) + _A1y * (q11) + _A1z * (-q10));

  _jachq->setValue(4, 0, 0);
  _jachq->setValue(4, 1, 0);
  _jachq->setValue(4, 2, 0);
  _jachq->setValue(4, 3, _A2x * (-q21) + _A2y * (-q22) + _A2z * (-q23));
  _jachq->setValue(4, 4, _A2x * (q20) + _A2y * (q23) + _A2z * (-q22));
  _jachq->setValue(4, 5, _A2x * (-q23) + _A2y * (q20) + _A2z * (q21));
  _jachq->setValue(4, 6, _A2x * (q22) + _A2y * (-q21) + _A2z * (q20));
  _jachq->setValue(4, 7, 0);
  _jachq->setValue(4, 8, 0);
  _jachq->setValue(4, 9, 0);
  _jachq->setValue(4, 10, _A2x * (q11) + _A2y * (q12) + _A2z * (q13));
  _jachq->setValue(4, 11, _A2x * (-q10) + _A2y * (-q13) + _A2z * (q12));
  _jachq->setValue(4, 12, _A2x * (q13) + _A2y * (-q10) + _A2z * (-q11));
  _jachq->setValue(4, 13, _A2x * (-q12) + _A2y * (q11) + _A2z * (-q10));

  //_jachq->display();
}

void PivotJointR::Jd1(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13)
{

  KneeJointR::Jd1(X1, Y1, Z1, q10, q11, q12, q13);

  _jachq->setValue(3, 0, 0);
  _jachq->setValue(3, 1, 0);
  _jachq->setValue(3, 2, 0);
  _jachq->setValue(3, 3, 0);
  _jachq->setValue(3, 4, _A1x);
  _jachq->setValue(3, 5, _A1y);
  _jachq->setValue(3, 6, _A1z);

  _jachq->setValue(4, 0, 0);
  _jachq->setValue(4, 1, 0);
  _jachq->setValue(4, 2, 0);
  _jachq->setValue(4, 3, 0);
  _jachq->setValue(4, 4, _A2x);
  _jachq->setValue(4, 5, _A2y);
  _jachq->setValue(4, 6, _A2z);

}

double PivotJointR::AscalA1(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
  ::boost::math::quaternion<float>    quat1(q10, q11, q12, q13);
  ::boost::math::quaternion<float>    quat2_inv(q20, -q21, -q22, -q23);
  ::boost::math::quaternion<float>    quatBuff = quat1 * quat2_inv;
  double aX = quatBuff.R_component_2();
  double aY = quatBuff.R_component_3();
  double aZ = quatBuff.R_component_4();
  return _A1x * aX + _A1y * aY + _A1z * aZ;
}
double PivotJointR::AscalA2(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
  ::boost::math::quaternion<float>    quat1(q10, q11, q12, q13);
  ::boost::math::quaternion<float>    quat2_inv(q20, -q21, -q22, -q23);
  ::boost::math::quaternion<float>    quatBuff = quat1 * quat2_inv;
  double aX = quatBuff.R_component_2();
  double aY = quatBuff.R_component_3();
  double aZ = quatBuff.R_component_4();
  return _A2x * aX + _A2y * aY + _A2z * aZ;
}
void PivotJointR::computeh(double t)
{
  KneeJointR::computeh(t);
  SP::SiconosVector x1 = _d1->q();
  //std::cout<<"PivotJoint computeH d1->q:\n";
  //x1->display();
  double q10 = x1->getValue(3);
  double q11 = x1->getValue(4);
  double q12 = x1->getValue(5);
  double q13 = x1->getValue(6);
  double q20 = 1;
  double q21 = 0;
  double q22 = 0;
  double q23 = 0;
  if (_d2)
  {
    SP::SiconosVector x2 = _d2->q();
    q20 = x2->getValue(3);
    q21 = x2->getValue(4);
    q22 = x2->getValue(5);
    q23 = x2->getValue(6);
  }

  SP::SiconosVector y = interaction()->y(0);
  y->setValue(3, AscalA1(q10, q11, q12, q13, q20, q21, q22, q23));
  y->setValue(4, AscalA2(q10, q11, q12, q13, q20, q21, q22, q23));

  std::cout << "PivotJoint computeH:\n";
  y->display();
}

<commit_msg>fix a bug:fabs(_Ax)<commit_after>/* Siconos-Kernel version 3.0.0, Copyright INRIA 2005-2008.
 * Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 * Siconos is a free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * Siconos 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Siconos; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Contact: Vincent ACARY vincent.acary@inrialpes.fr
 */
/*! \file PivotJoint.cpp

*/

#include "PivotJoint.hpp"
#include <boost/math/quaternion.hpp>

int PivotJointR::_sNbEqualities = 5;

PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::NewtonEulerDS d2, SP::SimpleVector P, SP::SimpleVector A): KneeJointR(d1, d2, P)
{
  SP::SiconosVector q1 = d1->q0();
  ::boost::math::quaternion<float>    quat1(q1->getValue(3), q1->getValue(4), q1->getValue(5), q1->getValue(6));
  ::boost::math::quaternion<float>    quatA(0, A->getValue(0), A->getValue(1), A->getValue(2));
  ::boost::math::quaternion<float>    quatBuff(0, 0, 0, 0);
  /*calcul of axis _A*/
  quatBuff = quat1 * quatA / quat1;
  _Ax = quatBuff.R_component_2();
  _Ay = quatBuff.R_component_3();
  _Az = quatBuff.R_component_4();
  buildA1A2();
}
/* constructor,
   \param a SP::NewtonEulerDS d1, a dynamical system containing the intial position
   \param a SP::SimpleVector P0, P0 contains the coordinates of the Pivot point, in the absolute frame.
*/
PivotJointR::PivotJointR(SP::NewtonEulerDS d1, SP::SimpleVector P0, SP::SimpleVector A): KneeJointR(d1, P0)
{

  _Ax = A->getValue(0);
  _Ay = A->getValue(1);
  _Az = A->getValue(2);
  buildA1A2();
}
void PivotJointR::buildA1A2()
{
  double normA = sqrt(_Ax * _Ax + _Ay * _Ay + _Az * _Az);
  assert(normA > 0.9 && "PivotJoint, normA to small\n");
  _Ax /= normA;
  _Ay /= normA;
  _Az /= normA;
  std::cout << "JointKnee: _Ax _Ay _Az :" << _Ax << " " << _Ay << " " << _Az << std::endl;
  /*build _A1*/
  if (fabs(_Ax) > fabs(_Ay))
  {
    if (fabs(_Ax) > fabs(_Az)) /*_Ax is the bigest*/
    {
      _A1x = _Ay;
      _A1y = -_Ax;
      _A1z = 0;
      _A2x = _Az;
      _A2z = -_Ax;
      _A2y = 0;
    }
    else  /*_Az is the biggest*/
    {
      _A1z = _Ax;
      _A1y = -_Az;
      _A1x = 0;
      _A2z = _Ay;
      _A2x = -_Az;
      _A2y = 0;
    }
  }
  else if (fabs(_Ay) > fabs(_Az))  /*_Ay is the bigest*/
  {
    _A1y = _Ax;
    _A1x = -_Ay;
    _A1z = 0;
    _A2y = _Az;
    _A2z = -_Ay;
    _A2x = 0;
  }
  else  /*_Az is the biggest*/
  {
    _A1z = _Ax;
    _A1y = -_Az;
    _A1x = 0;
    _A2z = _Ay;
    _A2x = -_Az;
    _A2y = 0;
  }
  assert(fabs(_A1x * _Ax + _A1y * _Ay + _A1z * _Az) < 1e-9 && "PivotJoint, _A1 wrong\n");
  assert(fabs(_A2x * _Ax + _A2y * _Ay + _A2z * _Az) < 1e-9 && "PivotJoint, _A2 wrong\n");
  assert(fabs(_A1x * _A2x + _A1y * _A2y + _A1z * _A2z) < 1e-9 && "PivotJoint, _A12 wrong\n");
  std::cout << "JointPivot: _A1x _A1y _A1z :" << _A1x << " " << _A1y << " " << _A1z << std::endl;
  std::cout << "JointPivot: _A2x _A2y _A2z :" << _A2x << " " << _A2y << " " << _A2z << std::endl;
}
void PivotJointR::Jd1d2(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13, double X2, double Y2, double Z2, double q20, double q21, double q22, double q23)
{
  KneeJointR::Jd1d2(X1, Y1, Z1, q10, q11, q12, q13, X2, Y2, Z2, q20, q21, q22, q23);

  _jachq->setValue(3, 0, 0);
  _jachq->setValue(3, 1, 0);
  _jachq->setValue(3, 2, 0);
  _jachq->setValue(3, 3, _A1x * (-q21) + _A1y * (-q22) + _A1z * (-q23));
  _jachq->setValue(3, 4, _A1x * (q20) + _A1y * (q23) + _A1z * (-q22));
  _jachq->setValue(3, 5, _A1x * (-q23) + _A1y * (q20) + _A1z * (q21));
  _jachq->setValue(3, 6, _A1x * (q22) + _A1y * (-q21) + _A1z * (q20));
  _jachq->setValue(3, 7, 0);
  _jachq->setValue(3, 8, 0);
  _jachq->setValue(3, 9, 0);
  _jachq->setValue(3, 10, _A1x * (q11) + _A1y * (q12) + _A1z * (q13));
  _jachq->setValue(3, 11, _A1x * (-q10) + _A1y * (-q13) + _A1z * (q12));
  _jachq->setValue(3, 12, _A1x * (q13) + _A1y * (-q10) + _A1z * (-q11));
  _jachq->setValue(3, 13, _A1x * (-q12) + _A1y * (q11) + _A1z * (-q10));

  _jachq->setValue(4, 0, 0);
  _jachq->setValue(4, 1, 0);
  _jachq->setValue(4, 2, 0);
  _jachq->setValue(4, 3, _A2x * (-q21) + _A2y * (-q22) + _A2z * (-q23));
  _jachq->setValue(4, 4, _A2x * (q20) + _A2y * (q23) + _A2z * (-q22));
  _jachq->setValue(4, 5, _A2x * (-q23) + _A2y * (q20) + _A2z * (q21));
  _jachq->setValue(4, 6, _A2x * (q22) + _A2y * (-q21) + _A2z * (q20));
  _jachq->setValue(4, 7, 0);
  _jachq->setValue(4, 8, 0);
  _jachq->setValue(4, 9, 0);
  _jachq->setValue(4, 10, _A2x * (q11) + _A2y * (q12) + _A2z * (q13));
  _jachq->setValue(4, 11, _A2x * (-q10) + _A2y * (-q13) + _A2z * (q12));
  _jachq->setValue(4, 12, _A2x * (q13) + _A2y * (-q10) + _A2z * (-q11));
  _jachq->setValue(4, 13, _A2x * (-q12) + _A2y * (q11) + _A2z * (-q10));

  //_jachq->display();
}

void PivotJointR::Jd1(double X1, double Y1, double Z1, double q10, double q11, double q12, double q13)
{

  KneeJointR::Jd1(X1, Y1, Z1, q10, q11, q12, q13);

  _jachq->setValue(3, 0, 0);
  _jachq->setValue(3, 1, 0);
  _jachq->setValue(3, 2, 0);
  _jachq->setValue(3, 3, 0);
  _jachq->setValue(3, 4, _A1x);
  _jachq->setValue(3, 5, _A1y);
  _jachq->setValue(3, 6, _A1z);

  _jachq->setValue(4, 0, 0);
  _jachq->setValue(4, 1, 0);
  _jachq->setValue(4, 2, 0);
  _jachq->setValue(4, 3, 0);
  _jachq->setValue(4, 4, _A2x);
  _jachq->setValue(4, 5, _A2y);
  _jachq->setValue(4, 6, _A2z);

}

double PivotJointR::AscalA1(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
  ::boost::math::quaternion<float>    quat1(q10, q11, q12, q13);
  ::boost::math::quaternion<float>    quat2_inv(q20, -q21, -q22, -q23);
  ::boost::math::quaternion<float>    quatBuff = quat1 * quat2_inv;
  double aX = quatBuff.R_component_2();
  double aY = quatBuff.R_component_3();
  double aZ = quatBuff.R_component_4();
  return _A1x * aX + _A1y * aY + _A1z * aZ;
}
double PivotJointR::AscalA2(double q10, double q11, double q12, double q13, double q20, double q21, double q22, double q23)
{
  ::boost::math::quaternion<float>    quat1(q10, q11, q12, q13);
  ::boost::math::quaternion<float>    quat2_inv(q20, -q21, -q22, -q23);
  ::boost::math::quaternion<float>    quatBuff = quat1 * quat2_inv;
  double aX = quatBuff.R_component_2();
  double aY = quatBuff.R_component_3();
  double aZ = quatBuff.R_component_4();
  return _A2x * aX + _A2y * aY + _A2z * aZ;
}
void PivotJointR::computeh(double t)
{
  KneeJointR::computeh(t);
  SP::SiconosVector x1 = _d1->q();
  //std::cout<<"PivotJoint computeH d1->q:\n";
  //x1->display();
  double q10 = x1->getValue(3);
  double q11 = x1->getValue(4);
  double q12 = x1->getValue(5);
  double q13 = x1->getValue(6);
  double q20 = 1;
  double q21 = 0;
  double q22 = 0;
  double q23 = 0;
  if (_d2)
  {
    SP::SiconosVector x2 = _d2->q();
    q20 = x2->getValue(3);
    q21 = x2->getValue(4);
    q22 = x2->getValue(5);
    q23 = x2->getValue(6);
  }

  SP::SiconosVector y = interaction()->y(0);
  y->setValue(3, AscalA1(q10, q11, q12, q13, q20, q21, q22, q23));
  y->setValue(4, AscalA2(q10, q11, q12, q13, q20, q21, q22, q23));

  std::cout << "PivotJoint computeH:\n";
  y->display();
}

<|endoftext|>


<commit_before>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciORBTask.cpp,v 1.4 2006/09/01 02:20:54 cparedes Exp $"
*
* who       when        what
* --------  ----------  ----------------------------------------------
* msekoran  2003/05/22  created
*/

#include <vltPort.h>

#include <maciORBTask.h>

 using namespace maci;

ORBTask::ORBTask (CORBA::ORB_ptr orb, LoggingProxy * logger, unsigned int timeToRun)
    :  m_orb(CORBA::ORB::_duplicate(orb)), m_logger(logger), m_timeToRun(timeToRun)
{
}

int
ORBTask::svc (void)
{
    // initialize logging
    if (m_logger)
      {
	LoggingProxy::init(m_logger);
	LoggingProxy::ThreadName("ORBTask");
      }

    try
      {

        // handle CORBA requests
	if (m_timeToRun == 0)
	  {
	    this->m_orb->run ();

	  }
	else
	  {
	    ACE_Time_Value tv (m_timeToRun);
	    this->m_orb->run (tv);

	  }

      }
    catch( CORBA::Exception &ex )
      {
	ACE_PRINT_EXCEPTION(ex, "maci::ORBTask::svc");
	return 1;
      }

  // return error free code
  return 0;
}

// ************************************************************************
//
// REVISION HISTORY:
//
// $Log: maciORBTask.cpp,v $
// Revision 1.4  2006/09/01 02:20:54  cparedes
// small change, NAMESPACE_BEGIN / NAMESPACE_END / NAMESPACE_USE macross to clean up a little the cpp code
//
// Revision 1.3  2005/09/27 08:35:10  vwang
//  change from ACE_TRY CATCH to C++ try catch
//
// Revision 1.2  2003/10/23 08:06:25  acaproni
// True native exception handling. No more extra parameters
//
// Revision 1.1  2003/05/23 09:26:37  msekoran
// Multi-threaded servers, hierarchical COBs reactivation deadlock fixed.
//
//
// ************************************************************************

<commit_msg>improved error handling<commit_after>/*******************************************************************************
* E.S.O. - ACS project
*
* "@(#) $Id: maciORBTask.cpp,v 1.5 2007/07/16 09:33:14 bjeram Exp $"
*
* who       when        what
* --------  ----------  ----------------------------------------------
* msekoran  2003/05/22  created
*/

#include <vltPort.h>

#include <maciORBTask.h>
#include <ACSErrTypeCommon.h>

 using namespace maci;

ORBTask::ORBTask (CORBA::ORB_ptr orb, LoggingProxy * logger, unsigned int timeToRun)
    :  m_orb(CORBA::ORB::_duplicate(orb)), m_logger(logger), m_timeToRun(timeToRun)
{
}

int
ORBTask::svc (void)
{
    // initialize logging
    if (m_logger)
      {
	LoggingProxy::init(m_logger);
	LoggingProxy::ThreadName("ORBTask");
      }

    try
      {

        // handle CORBA requests
	if (m_timeToRun == 0)
	  {
	    this->m_orb->run ();

	  }
	else
	  {
	    ACE_Time_Value tv (m_timeToRun);
	    this->m_orb->run (tv);

	  }

      }
    catch( CORBA::SystemException &ex )
	{
	ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__,
							    "maci::ORBTask::svc");
	corbaProblemEx.setMinor(ex.minor());
	corbaProblemEx.setCompletionStatus(ex.completed());
	corbaProblemEx.setInfo(ex._info().c_str());

	corbaProblemEx.log();
	return 1;
	}
    catch( CORBA::Exception &ex )
      {
      ACSErrTypeCommon::CORBAProblemExImpl corbaProblemEx(__FILE__, __LINE__,
							    "maci::ORBTask::svc");
      corbaProblemEx.setInfo(ex._info().c_str());
      corbaProblemEx.log();
      return 1;
      }
    catch(ACSErr::ACSbaseExImpl &_ex)
	{

	ACSErrTypeCommon::UnexpectedExceptionExImpl ex(_ex, __FILE__, __LINE__,
						       "maci::ORBTask::svc");
	ex.log();
	return 1;
	}
    catch(...)
	{
	ACSErrTypeCommon::UnexpectedExceptionExImpl ex(__FILE__, __LINE__,
						       "maci::ORBTask::svc");
	ex.log();
	return 1;
	}//try-catch

  // return error free code
  return 0;
}

// ************************************************************************
//
// REVISION HISTORY:
//
// $Log: maciORBTask.cpp,v $
// Revision 1.5  2007/07/16 09:33:14  bjeram
// improved error handling
//
// Revision 1.4  2006/09/01 02:20:54  cparedes
// small change, NAMESPACE_BEGIN / NAMESPACE_END / NAMESPACE_USE macross to clean up a little the cpp code
//
// Revision 1.3  2005/09/27 08:35:10  vwang
//  change from ACE_TRY CATCH to C++ try catch
//
// Revision 1.2  2003/10/23 08:06:25  acaproni
// True native exception handling. No more extra parameters
//
// Revision 1.1  2003/05/23 09:26:37  msekoran
// Multi-threaded servers, hierarchical COBs reactivation deadlock fixed.
//
//
// ************************************************************************

<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-5-26 21:31:42
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, Q;
ll S[200010], T[200010], X[200010];
ll D[200010];
int ans[200010];
typedef tuple<ll, ll, ll, int> K;
vector<K> KK;
typedef tuple<ll, int, int> info;
priority_queue<info, vector<info>, greater<info>> P;

int main()
{
  cin >> N >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> S[i] >> T[i] >> X[i];
    KK.push_back(K(X[i], S[i], T[i], i));
  }
  sort(KK.begin(), KK.end());
  for (auto i = 0; i < Q; i++)
  {
    cin >> D[i];
  }
  for (auto i = 0; i < N; i++)
  {
    ll x = get<0>(KK[i]);
    ll s = get<1>(KK[i]);
    ll t = get<2>(KK[i]);
    int ind = get<3>(KK[i]);
    P.push(info(s - x, ind, 0));
    P.push(info(t - x, ind, 1));
  }
  int ind = 0;
  set<int> S;
  fill(ans, ans + Q, -1);
  while (!P.empty())
  {
    info x = P.top();
    P.pop();
    ll next_t = get<0>(x);
    int point = get<1>(x);
    bool start = (get<2>(x) == 0);
    while (next_t > D[ind])
    {
      int a = -1;
      if (S.empty())
      {
        a = -1;
      }
      else
      {
        a = *S.begin();
      }
      ans[ind] = a;
      ind++;
      if (ind == Q)
      {
        goto EXIT;
      }
    }
    if (start)
    {
      S.insert(point);
    }
    else
    {
      S.erase(S.find(point));
    }
  }
EXIT:
  for (auto i = 0; i < Q; i++)
  {
    if (ans[i] == -1)
    {
      cout << -1 << endl;
    }
    else
    {
      cout << X[ans[i]] << endl;
    }
  }
}<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1

/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 2019-5-26 21:31:42
 * Powered by Visual Studio Code
 */

#include <iostream>
#include <iomanip>   // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set>
#include <functional>
#include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010));
#include <chrono> // std::chrono::system_clock::time_point start_time, end_time;
// start = std::chrono::system_clock::now();
// double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count();
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

typedef long long ll;

// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

// const int C = 1e6+10;
// const ll M = 1000000007;

int N, Q;
ll S[200010], T[200010], X[200010];
ll D[200010];
int ans[200010];
typedef tuple<ll, ll, ll, int> K;
vector<K> KK;
typedef tuple<ll, int, int> info;
priority_queue<info, vector<info>, greater<info>> P;

int main()
{
  cin >> N >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> S[i] >> T[i] >> X[i];
    KK.push_back(K(X[i], S[i], T[i], i));
  }
  sort(KK.begin(), KK.end());
  for (auto i = 0; i < Q; i++)
  {
    cin >> D[i];
  }
  for (auto i = 0; i < N; i++)
  {
    ll x = get<0>(KK[i]);
    ll s = get<1>(KK[i]);
    ll t = get<2>(KK[i]);
    int ind = get<3>(KK[i]);
    P.push(info(s - x, ind, 0));
    P.push(info(t - x, ind, 1));
  }
  int ind = 0;
  set<int> S;
  fill(ans, ans + Q, -1);
  while (!P.empty())
  {
    info x = P.top();
    P.pop();
    ll next_t = get<0>(x);
    int point = get<1>(x);
    bool start = (get<2>(x) == 0);
#if DEBUG == 1
    cerr << "next_t = " << next_t << endl;
#endif
    while (next_t > D[ind])
    {
      int a = -1;
      if (S.empty())
      {
        a = -1;
      }
      else
      {
        a = *S.begin();
      }
      ans[ind] = a;
#if DEBUG == 1
      cerr << "ans[" << ind << "] = " << ans[ind] << endl;
#endif
      ind++;
      if (ind == Q)
      {
        goto EXIT;
      }
    }
    if (start)
    {
      S.insert(point);
#if DEBUG == 1
      cerr << "insert: " << point << endl;
#endif
    }
    else
    {
      S.erase(S.find(point));
#if DEBUG == 1
      cerr << "erase: " << point << endl;
#endif
    }
  }
EXIT:
  for (auto i = 0; i < Q; i++)
  {
    if (ans[i] == -1)
    {
      cout << -1 << endl;
    }
    else
    {
      cout << X[ans[i]] << endl;
    }
  }
}<|endoftext|>


<commit_before>#ifndef CRYPTO_HPP
#define	CRYPTO_HPP

#include <string>
#include <cmath>

//Moving these to a seperate namespace for minimal global namespace cluttering does not work with clang++
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/sha.h>
#include <openssl/md5.h>

namespace SimpleWeb {
    //type must support size(), resize() and operator[]
    namespace Crypto {
        namespace Base64 {
            template<class type>
            void encode(const type& ascii, type& base64) {
                BIO *bio, *b64;
                BUF_MEM *bptr;

                b64 = BIO_new(BIO_f_base64());
                BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
                bio = BIO_new(BIO_s_mem());
                BIO_push(b64, bio);
                BIO_get_mem_ptr(b64, &bptr);

                //Write directly to base64-buffer to avoid copy
                int base64_length=round(4*ceil((double)ascii.size()/3.0));
                base64.resize(base64_length);
                bptr->length=0;
                bptr->max=base64_length+1;
                bptr->data=(char*)&base64[0];

                BIO_write(b64, &ascii[0], ascii.size());
                BIO_flush(b64);

                //To keep &base64[0] through BIO_free_all(b64)
                bptr->length=0;
                bptr->max=0;
                bptr->data=nullptr;

                BIO_free_all(b64);
            }
            template<class type>
            type encode(const type& ascii) {
                type base64;
                encode(ascii, base64);
                return base64;
            }

            template<class type>
            void decode(const type& base64, type& ascii) {
                //Resize ascii, however, the size is a up to two bytes too large.
                ascii.resize((6*base64.size())/8);
                BIO *b64, *bio;

                b64 = BIO_new(BIO_f_base64());
                BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
                bio = BIO_new_mem_buf((char*)&base64[0], base64.size());
                bio = BIO_push(b64, bio);

                int decoded_length = BIO_read(bio, &ascii[0], ascii.size());
                ascii.resize(decoded_length);

                BIO_free_all(b64);
            }
            template<class type>
            type decode(const type& base64) {
                type ascii;
                decode(base64, ascii);
                return ascii;
            }

        }

        template<class type>
        void MD5(const type& input, type& hash) {
            hash.resize(128/8);

            MD5_CTX context;
            MD5_Init(&context);
            MD5_Update(&context, &input[0], input.size());
            MD5_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type MD5(const type& input) {
            type hash;
            MD5(input, hash);
            return hash;
        }

        template<class type>
        void SHA1(const type& input, type& hash) {
            hash.resize(160/8);

            SHA_CTX context;
            SHA1_Init(&context);
            SHA1_Update(&context, &input[0], input.size());
            SHA1_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type SHA1(const type& input) {
            type hash;
            SHA1(input, hash);
            return hash;
        }

        template<class type>
        void SHA256(const type& input, type& hash) {
            hash.resize(256/8);

            SHA256_CTX context;
            SHA256_Init(&context);
            SHA256_Update(&context, &input[0], input.size());
            SHA256_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type SHA256(const type& input) {
            type hash;
            SHA256(input, hash);
            return hash;
        }

        template<class type>
        void SHA512(const type& input, type& hash) {
            hash.resize(512/8);

            SHA512_CTX context;
            SHA512_Init(&context);
            SHA512_Update(&context, &input[0], input.size());
            SHA512_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type SHA512(const type& input) {
            type hash;
            SHA512(input, hash);
            return hash;
        }
    }
}
#endif	/* CRYPTO_HPP */

<commit_msg>Hash functions can now be run iteratively with the two-parameter versions.<commit_after>#ifndef CRYPTO_HPP
#define	CRYPTO_HPP

#include <string>
#include <cmath>

//Moving these to a seperate namespace for minimal global namespace cluttering does not work with clang++
#include <openssl/evp.h>
#include <openssl/buffer.h>
#include <openssl/sha.h>
#include <openssl/md5.h>

namespace SimpleWeb {
    //type must support size(), resize() and operator[]
    namespace Crypto {
        namespace Base64 {
            template<class type>
            void encode(const type& ascii, type& base64) {
                BIO *bio, *b64;
                BUF_MEM *bptr;

                b64 = BIO_new(BIO_f_base64());
                BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
                bio = BIO_new(BIO_s_mem());
                BIO_push(b64, bio);
                BIO_get_mem_ptr(b64, &bptr);

                //Write directly to base64-buffer to avoid copy
                int base64_length=round(4*ceil((double)ascii.size()/3.0));
                base64.resize(base64_length);
                bptr->length=0;
                bptr->max=base64_length+1;
                bptr->data=(char*)&base64[0];

                BIO_write(b64, &ascii[0], ascii.size());
                BIO_flush(b64);

                //To keep &base64[0] through BIO_free_all(b64)
                bptr->length=0;
                bptr->max=0;
                bptr->data=nullptr;

                BIO_free_all(b64);
            }
            template<class type>
            type encode(const type& ascii) {
                type base64;
                encode(ascii, base64);
                return base64;
            }

            template<class type>
            void decode(const type& base64, type& ascii) {
                //Resize ascii, however, the size is a up to two bytes too large.
                ascii.resize((6*base64.size())/8);
                BIO *b64, *bio;

                b64 = BIO_new(BIO_f_base64());
                BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
                bio = BIO_new_mem_buf((char*)&base64[0], base64.size());
                bio = BIO_push(b64, bio);

                int decoded_length = BIO_read(bio, &ascii[0], ascii.size());
                ascii.resize(decoded_length);

                BIO_free_all(b64);
            }
            template<class type>
            type decode(const type& base64) {
                type ascii;
                decode(base64, ascii);
                return ascii;
            }

        }

        template<class type>
        void MD5(const type& input, type& hash) {
            MD5_CTX context;
            MD5_Init(&context);
            MD5_Update(&context, &input[0], input.size());

            hash.resize(128/8);
            MD5_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type MD5(const type& input) {
            type hash;
            MD5(input, hash);
            return hash;
        }

        template<class type>
        void SHA1(const type& input, type& hash) {
            SHA_CTX context;
            SHA1_Init(&context);
            SHA1_Update(&context, &input[0], input.size());

            hash.resize(160/8);
            SHA1_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type SHA1(const type& input) {
            type hash;
            SHA1(input, hash);
            return hash;
        }

        template<class type>
        void SHA256(const type& input, type& hash) {
            SHA256_CTX context;
            SHA256_Init(&context);
            SHA256_Update(&context, &input[0], input.size());

            hash.resize(256/8);
            SHA256_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type SHA256(const type& input) {
            type hash;
            SHA256(input, hash);
            return hash;
        }

        template<class type>
        void SHA512(const type& input, type& hash) {
            SHA512_CTX context;
            SHA512_Init(&context);
            SHA512_Update(&context, &input[0], input.size());

            hash.resize(512/8);
            SHA512_Final((unsigned char*)&hash[0], &context);
        }
        template<class type>
        type SHA512(const type& input) {
            type hash;
            SHA512(input, hash);
            return hash;
        }
    }
}
#endif	/* CRYPTO_HPP */

<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 6/11/2019, 7:17:01 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % MOD) {}
  mint operator-() const { return mint(0) - *this; }
  mint &operator+=(const mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  mint &operator-=(const mint &a) { return *this += -a; }
  mint &operator*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
  mint operator+(const mint &a) const { return mint(*this) += a; }
  mint operator-(const mint &a) const { return mint(*this) -= a; }
  mint operator*(const mint &a) const { return mint(*this) *= a; }
  mint operator/(const mint &a) const { return mint(*this) /= a; }
  bool operator<(const mint &a) const { return x < a.x; }
  bool operator==(const mint &a) const { return x == a.x; }
  const mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      mint half = power(N / 2);
      return half * half;
    }
  }
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = mint(i) * fact[i - 1];
    factinv[i] = inv[i] * factinv[i - 1];
  }
}
mint choose(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return fact[n] * factinv[k] * factinv[n - k];
  }
  return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

int H, W;
string S[100010];
int X[2010][2010];
int Y[2010][2010];

int main()
{
  // init();
  cin >> H >> W;
  for (auto i = 0; i < H; i++)
  {
    cin >> S[i];
  }
  for (auto i = 0; i < H; i++)
  {
    int t = 0;
    for (auto j = 0; j < W; j++)
    {
      if (S[i][j] == '.')
      {
        t++;
      }
      else
      {
        for (auto k = j - 1; k >= j - t; k--)
        {
          X[i][k] = t;
        }
      }
    }
    for (auto k = W - 1; k >= W - t; k--)
    {
      X[i][k] = t;
    }
  }
  for (auto j = 0; j < W; j++)
  {
    int t = 0;
    for (auto i = 0; i < H; i++)
    {
      if (S[i][j] == '.')
      {
        t++;
      }
      else
      {
        for (auto k = i - 1; k >= i - t; k--)
        {
          Y[k][j] = t;
        }
      }
    }
    for (auto k = H - 1; k >= H - t; k--)
    {
      Y[k][j] = t;
    }
  }
  int ans = 0;
  for (auto i = 0; i < H; i++)
  {
    for (auto j = 0; j < W; j++)
    {
      maxs(ans, X[i][j] + Y[i][j] - 1);
    }
  }
  cout << ans << endl;
}<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1
/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 6/11/2019, 7:17:01 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % MOD) {}
  mint operator-() const { return mint(0) - *this; }
  mint &operator+=(const mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  mint &operator-=(const mint &a) { return *this += -a; }
  mint &operator*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
  mint operator+(const mint &a) const { return mint(*this) += a; }
  mint operator-(const mint &a) const { return mint(*this) -= a; }
  mint operator*(const mint &a) const { return mint(*this) *= a; }
  mint operator/(const mint &a) const { return mint(*this) /= a; }
  bool operator<(const mint &a) const { return x < a.x; }
  bool operator==(const mint &a) const { return x == a.x; }
  const mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      mint half = power(N / 2);
      return half * half;
    }
  }
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = mint(i) * fact[i - 1];
    factinv[i] = inv[i] * factinv[i - 1];
  }
}
mint choose(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return fact[n] * factinv[k] * factinv[n - k];
  }
  return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};

int H, W;
string S[100010];
int X[2010][2010];
int Y[2010][2010];

int main()
{
  // init();
  cin >> H >> W;
  for (auto i = 0; i < H; i++)
  {
    cin >> S[i];
  }
  for (auto i = 0; i < H; i++)
  {
    int t = 0;
    for (auto j = 0; j < W; j++)
    {
      if (S[i][j] == '.')
      {
        t++;
      }
      else
      {
        for (auto k = j - 1; k >= j - t; k--)
        {
          X[i][k] = t;
        }
      }
    }
    for (auto k = W - 1; k >= W - t; k--)
    {
      X[i][k] = t;
    }
  }
  for (auto j = 0; j < W; j++)
  {
    int t = 0;
    for (auto i = 0; i < H; i++)
    {
      if (S[i][j] == '.')
      {
        t++;
      }
      else
      {
        for (auto k = i - 1; k >= i - t; k--)
        {
          Y[k][j] = t;
        }
      }
    }
    for (auto k = H - 1; k >= H - t; k--)
    {
      Y[k][j] = t;
    }
  }
#if DEBUG == 1
  cerr << "X:" << endl;
  for (auto i = 0; i < H; i++)
  {
    for (auto j = 0; j < W; j++)
    {
      cerr << X[i][j];
    }
    cerr << endl;
  }
  cerr << "Y:" << endl;
  for (auto i = 0; i < H; i++)
  {
    for (auto j = 0; j < W; j++)
    {
      cerr << Y[i][j];
    }
    cerr << endl;
  }
#endif
  int ans = 0;
  for (auto i = 0; i < H; i++)
  {
    for (auto j = 0; j < W; j++)
    {
      maxs(ans, X[i][j] + Y[i][j] - 1);
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 6/18/2019, 2:02:05 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
  cout << "YES" << endl;
  exit(0);
}
void No()
{
  cout << "NO" << endl;
  exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % MOD) {}
  mint operator-() const { return x ? MOD - x : 0; }
  mint &operator+=(const mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  mint &operator-=(const mint &a) { return *this += -a; }
  mint &operator*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
  mint operator+(const mint &a) const { return mint(*this) += a; }
  mint operator-(const mint &a) const { return mint(*this) -= a; }
  mint operator*(const mint &a) const { return mint(*this) *= a; }
  mint operator/(const mint &a) const { return mint(*this) /= a; }
  bool operator<(const mint &a) const { return x < a.x; }
  bool operator==(const mint &a) const { return x == a.x; }
  const mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      mint half = power(N / 2);
      return half * half;
    }
  }
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = mint(i) * fact[i - 1];
    factinv[i] = inv[i] * factinv[i - 1];
  }
}
mint choose(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return fact[n] * factinv[k] * factinv[n - k];
  }
  return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
const int dx[8] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};

typedef vector<string> ban;
const int C = 19;

enum class state
{
  black_win,
  white_win,
  black_even,
  white_even,
  error,
};

class Go
{
public:
  ban B;
  vector<int> cnt = vector<int>(2, 0);
  Go() {}
  Go(ban V) : B(V)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        if (B[i][j] == 'o')
        {
          cnt[0]++;
        }
        else if (B[i][j] == 'x')
        {
          cnt[1]++;
        }
      }
    }
  }

  bool win(char c)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        for (auto a = 0; a < 8; a++)
        {
          bool ok = true;
          for (auto k = 0; k < 5; k++)
          {
            int x = i + dx[a] * k;
            int y = j + dy[a] * k;
            if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
            {
              ok = false;
              break;
            }
          }
          if (ok)
          {
            return true;
          }
        }
      }
    }
    return false;
  }

  state st()
  {
    int t = cnt[0] - cnt[1];
    if (!(t == 0 || t == 1))
    {
      return state::error;
    }
    bool black_turn = (t == 1);
    bool black_win = win('o');
    bool white_win = win('x');
    if (black_win && white_win)
    {
      return state::error;
    }
    else if (black_win)
    {
      if (black_turn)
      {
        return state::black_win;
      }
      else
      {
        return state::error;
      }
    }
    else if (white_win)
    {
      if (!black_turn)
      {
        return state::white_win;
      }
      else
      {
        return state::error;
      }
    }
    else
    {
      if (black_turn)
      {
        return state::black_even;
      }
      else
      {
        return state::white_even;
      }
    }
  }
};

int main()
{
  // init();
  ban B;
  for (auto i = 0; i < C; i++)
  {
    string S;
    cin >> S;
    B.push_back(S);
  }
  Go I(B);
  state I_state = I.st();
#if DEBUG == 1
  cerr << I.cnt[0] << " VS " << I.cnt[1] << endl;
  cerr << "I_state: " << (int)I_state << endl;
#endif
  if (I_state == state::error)
  {
    No();
  }
  if (I_state == state::white_even || I_state == state::black_even)
  {
    assert(false);
    Yes();
  }
  if (I_state == state::black_win)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        if (B[i][j] == 'o')
        {
          ban V = B;
          V[i][j] = '.';
          Go before(V);
          if (before.st() == state::white_even)
          {
#if DEBUG == 1
            cerr << "Prev Board: " << endl;
            cerr << before.cnt[0] << " VS " << before.cnt[1] << endl;
            for (auto i = 0; i < C; i++)
            {
              cerr << before.B[i] << endl;
            }
#endif
            Yes();
          }
        }
      }
    }
    No();
  }
  if (I_state == state::white_win)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        if (B[i][j] == 'x')
        {
          ban V = B;
          V[i][j] = '.';
          Go before(V);
          if (before.st() == state::black_even)
          {
#if DEBUG == 1
            cerr << "Prev Board: " << endl;
            for (auto i = 0; i < C; i++)
            {
              cerr << before.B[i] << endl;
            }
#endif
            Yes();
          }
        }
      }
    }
    No();
  }
}<commit_msg>submit C.cpp to 'C - 五目並べチェッカー' (arc012) [C++14 (GCC 5.4.1)]<commit_after>#define DEBUG 1
/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 6/18/2019, 2:02:05 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
typedef long long ll;
void Yes()
{
  cout << "YES" << endl;
  exit(0);
}
void No()
{
  cout << "NO" << endl;
  exit(0);
}
const int MAX_SIZE = 1000010;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % MOD) {}
  mint operator-() const { return x ? MOD - x : 0; }
  mint &operator+=(const mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  mint &operator-=(const mint &a) { return *this += -a; }
  mint &operator*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a) { return (*this *= power(MOD - 2)); }
  mint operator+(const mint &a) const { return mint(*this) += a; }
  mint operator-(const mint &a) const { return mint(*this) -= a; }
  mint operator*(const mint &a) const { return mint(*this) *= a; }
  mint operator/(const mint &a) const { return mint(*this) /= a; }
  bool operator<(const mint &a) const { return x < a.x; }
  bool operator==(const mint &a) const { return x == a.x; }
  const mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      mint half = power(N / 2);
      return half * half;
    }
  }
};
ll mint::MOD = 1e9 + 7;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
mint inv[MAX_SIZE];
mint fact[MAX_SIZE];
mint factinv[MAX_SIZE];
void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = mint(i) * fact[i - 1];
    factinv[i] = inv[i] * factinv[i - 1];
  }
}
mint choose(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return fact[n] * factinv[k] * factinv[n - k];
  }
  return 0;
}
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// const double epsilon = 1e-10;
// const ll infty = 1000000000000000LL;
const int dx[8] = {1, 0, -1, 0, 1, -1, 1, -1};
const int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};

typedef vector<string> ban;
const int C = 19;

enum class state
{
  black_win,
  white_win,
  black_even,
  white_even,
  error,
};

class Go
{
public:
  ban B;
  vector<int> cnt = vector<int>(2, 0);
  Go() {}
  Go(ban V) : B(V)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        if (B[i][j] == 'o')
        {
          cnt[0]++;
        }
        else if (B[i][j] == 'x')
        {
          cnt[1]++;
        }
      }
    }
  }

  bool win(char c)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        for (auto a = 0; a < 8; a++)
        {
          bool ok = true;
          for (auto k = 0; k < 5; k++)
          {
            int x = i + dx[a] * k;
            int y = j + dy[a] * k;
            if (0 <= x && x < C && 0 <= y && y < C && B[x][y] != c)
            {
              ok = false;
              break;
            }
          }
          if (ok)
          {
            return true;
          }
        }
      }
    }
    return false;
  }

  state st()
  {
    int t = cnt[0] - cnt[1];
    if (!(t == 0 || t == 1))
    {
      return state::error;
    }
    bool black_turn = (t == 1);
    bool black_win = win('o');
    bool white_win = win('x');
    if (black_win && white_win)
    {
      return state::error;
    }
    else if (black_win)
    {
      if (black_turn)
      {
        return state::black_win;
      }
      else
      {
        return state::error;
      }
    }
    else if (white_win)
    {
      if (!black_turn)
      {
        return state::white_win;
      }
      else
      {
        return state::error;
      }
    }
    else
    {
      if (black_turn)
      {
        return state::black_even;
      }
      else
      {
        return state::white_even;
      }
    }
  }
};

int main()
{
  // init();
  ban B;
  for (auto i = 0; i < C; i++)
  {
    string S;
    cin >> S;
    B.push_back(S);
  }
  Go I(B);
  state I_state = I.st();
#if DEBUG == 1
  cerr << I.cnt[0] << " VS " << I.cnt[1] << endl;
  cerr << "I_state: " << (int)I_state << endl;
#endif
  if (I_state == state::error)
  {
    assert(false);
    No();
  }
  if (I_state == state::white_even || I_state == state::black_even)
  {
    Yes();
  }
  if (I_state == state::black_win)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        if (B[i][j] == 'o')
        {
          ban V = B;
          V[i][j] = '.';
          Go before(V);
          if (before.st() == state::white_even)
          {
#if DEBUG == 1
            cerr << "Prev Board: " << endl;
            cerr << before.cnt[0] << " VS " << before.cnt[1] << endl;
            for (auto i = 0; i < C; i++)
            {
              cerr << before.B[i] << endl;
            }
#endif
            Yes();
          }
        }
      }
    }
    No();
  }
  if (I_state == state::white_win)
  {
    for (auto i = 0; i < C; i++)
    {
      for (auto j = 0; j < C; j++)
      {
        if (B[i][j] == 'x')
        {
          ban V = B;
          V[i][j] = '.';
          Go before(V);
          if (before.st() == state::black_even)
          {
#if DEBUG == 1
            cerr << "Prev Board: " << endl;
            for (auto i = 0; i < C; i++)
            {
              cerr << before.B[i] << endl;
            }
#endif
            Yes();
          }
        }
      }
    }
    No();
  }
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 8/5/2019, 1:06:42 AM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % MOD) {}
  mint operator-() const { return x ? MOD - x : 0; }
  mint &operator+=(const mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  mint &operator-=(const mint &a) { return *this += -a; }
  mint &operator*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a)
  {
    mint b{a};
    return *this *= b.power(MOD - 2);
  }
  mint operator+(const mint &a) const { return mint(*this) += a; }
  mint operator-(const mint &a) const { return mint(*this) -= a; }
  mint operator*(const mint &a) const { return mint(*this) *= a; }
  mint operator/(const mint &a) const { return mint(*this) /= a; }
  bool operator<(const mint &a) const { return x < a.x; }
  bool operator==(const mint &a) const { return x == a.x; }
  const mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      mint half = power(N / 2);
      return half * half;
    }
  }
};
ll mint::MOD = 998244353;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
  vector<mint> inv, fact, factinv;
  static int MAX_SIZE;
  combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1; i < MAX_SIZE; i++)
    {
      fact[i] = mint(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  mint operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

template <typename T>
class SegTree
{ // 0-indexed, [0, N).
private:
  int N;
  T *dat;
  T UNIT; // モノイドの単位元

  static T func(T x, T y)
  { // ここで演算を定義する。圏、特にモノイドであればなんでも良い。
    // 実装はモノイドであるとする。
    // return min(x, y);
    return x + y;
  }

  static T _update(T x, T y)
  { // update で 値をどうするかを書く。
    // return y;
    return func(x, y);
  }

public:
  SegTree() {}

  SegTree(int n, T unit)
  { // ここで unit を定義するのも変な実装だけどめんどいからこれでいい。
    // min の場合は INFTY = (1LL << 60)
    // + の場合は 0 とする。
    UNIT = unit;
    N = 1;
    while (N < n)
    {
      N *= 2;
    }
    dat = new T[2 * N - 1];
    for (auto i = 0; i < 2 * N - 1; ++i)
    {
      dat[i] = UNIT;
    }
  }

  void update(int k, T a)
  {
    k += N - 1;
    dat[k] = _update(dat[k], a);
    while (k > 0)
    {
      k = (k - 1) / 2;
      dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]);
    }
  }

private:
  T find(int a, int b, int k, int l, int r)
  {
    if (r <= a || b <= l)
      return UNIT;
    if (a <= l && r <= b)
      return dat[k];
    T vl = find(a, b, k * 2 + 1, l, (l + r) / 2);
    T vr = find(a, b, k * 2 + 2, (l + r) / 2, r);
    return func(vl, vr);
  }

public:
  T find(int a, int b)
  { // [a, b) の find をする。
    return find(a, b, 0, 0, N);
  }
};

using info = tuple<ll, ll, ll, ll>;
using point = tuple<ll, ll, int>;

int N;
vector<point> V;
vector<info> I;

mint f(info x)
{
  ll a, b, c, d;
  tie(a, b, c, d) = x;
  mint res = 0;
#if DEBUG == 1
  cerr << "(" << a << ", " << b << ", " << c << ", " << d << ")" << endl;
#endif
  res += mint{2}.power(N) - 1;
  res -= mint{2}.power(a + b);
  res -= mint{2}.power(a + c);
  res -= mint{2}.power(b + d);
  res -= mint{2}.power(c + d);
  res += mint{2}.power(a);
  res += mint{2}.power(b);
  res += mint{2}.power(c);
  res += mint{2}.power(d);
#if DEBUG == 1
  cerr << res << endl;
#endif
  return res;
}

int main()
{
  cin >> N;
  set<int> set_x, set_y;
  for (auto i = 0; i < N; i++)
  {
    int x, y;
    cin >> x >> y;
    V.emplace_back(x, y, i);
    set_x.insert(x);
    set_y.insert(y);
  }
  I.resize(N);
  map<int, int> map_x, map_y;
  {
    auto it = set_x.begin();
    for (auto i = 0; i < N; i++)
    {
      map_x[*it] = i;
      ++it;
    }
  }
  {
    auto it = set_y.begin();
    for (auto i = 0; i < N; i++)
    {
      map_y[*it] = i;
      ++it;
    }
  }
  for (auto i = 0; i < N; i++)
  {
    get<0>(V[i]) = map_x[get<0>(V[i])];
    get<1>(V[i]) = map_y[get<0>(V[i])];
  }
  sort(V.begin(), V.end());
  {
    SegTree<ll> tree{N, 0};
    for (auto i = 0; i < N; i++)
    {
      int x, y, ind;
      tie(x, y, ind) = V[i];
      ll k = tree.find(0, y);
      get<0>(I[ind]) = k;
      get<1>(I[ind]) = i - k;
      tree.update(y, 1);
    }
  }
  reverse(V.begin(), V.end());
  {
    SegTree<ll> tree{N, 0};
    for (auto i = 0; i < N; i++)
    {
      int x, y, ind;
      tie(x, y, ind) = V[i];
      ll k = tree.find(0, y);
      get<2>(I[ind]) = k;
      get<3>(I[ind]) = i - k;
      tree.update(y, 1);
    }
  }
  mint ans = 0;
  for (auto i = 0; i < N; i++)
  {
    ans += f(I[i]);
  }
  cout << ans << endl;
}<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1
/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 8/5/2019, 1:06:42 AM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
#define maxs(x, y) (x = max(x, y))
#define mins(x, y) (x = min(x, y))
using ll = long long;
class mint
{
public:
  static ll MOD;
  ll x;
  mint() : x(0) {}
  mint(ll x) : x(x % MOD) {}
  mint operator-() const { return x ? MOD - x : 0; }
  mint &operator+=(const mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  mint &operator-=(const mint &a) { return *this += -a; }
  mint &operator*=(const mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  mint &operator/=(const mint &a)
  {
    mint b{a};
    return *this *= b.power(MOD - 2);
  }
  mint operator+(const mint &a) const { return mint(*this) += a; }
  mint operator-(const mint &a) const { return mint(*this) -= a; }
  mint operator*(const mint &a) const { return mint(*this) *= a; }
  mint operator/(const mint &a) const { return mint(*this) /= a; }
  bool operator<(const mint &a) const { return x < a.x; }
  bool operator==(const mint &a) const { return x == a.x; }
  const mint power(ll N)
  {
    if (N == 0)
    {
      return 1;
    }
    else if (N % 2 == 1)
    {
      return *this * power(N - 1);
    }
    else
    {
      mint half = power(N / 2);
      return half * half;
    }
  }
};
ll mint::MOD = 998244353;
istream &operator>>(istream &stream, mint &a) { return stream >> a.x; }
ostream &operator<<(ostream &stream, const mint &a) { return stream << a.x; }
class combination
{
public:
  vector<mint> inv, fact, factinv;
  static int MAX_SIZE;
  combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE)
  {
    inv[1] = 1;
    for (auto i = 2; i < MAX_SIZE; i++)
    {
      inv[i] = (-inv[mint::MOD % i]) * (mint::MOD / i);
    }
    fact[0] = factinv[0] = 1;
    for (auto i = 1; i < MAX_SIZE; i++)
    {
      fact[i] = mint(i) * fact[i - 1];
      factinv[i] = inv[i] * factinv[i - 1];
    }
  }
  mint operator()(int n, int k)
  {
    if (n >= 0 && k >= 0 && n - k >= 0)
    {
      return fact[n] * factinv[k] * factinv[n - k];
    }
    return 0;
  }
};
int combination::MAX_SIZE = 3000010;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// constexpr double epsilon = 1e-10;
// constexpr ll infty = 1000000000000000LL;
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

template <typename T>
class SegTree
{ // 0-indexed, [0, N).
private:
  int N;
  T *dat;
  T UNIT; // モノイドの単位元

  static T func(T x, T y)
  { // ここで演算を定義する。圏、特にモノイドであればなんでも良い。
    // 実装はモノイドであるとする。
    // return min(x, y);
    return x + y;
  }

  static T _update(T x, T y)
  { // update で 値をどうするかを書く。
    // return y;
    return func(x, y);
  }

public:
  SegTree() {}

  SegTree(int n, T unit)
  { // ここで unit を定義するのも変な実装だけどめんどいからこれでいい。
    // min の場合は INFTY = (1LL << 60)
    // + の場合は 0 とする。
    UNIT = unit;
    N = 1;
    while (N < n)
    {
      N *= 2;
    }
    dat = new T[2 * N - 1];
    for (auto i = 0; i < 2 * N - 1; ++i)
    {
      dat[i] = UNIT;
    }
  }

  void update(int k, T a)
  {
    k += N - 1;
    dat[k] = _update(dat[k], a);
    while (k > 0)
    {
      k = (k - 1) / 2;
      dat[k] = func(dat[k * 2 + 1], dat[k * 2 + 2]);
    }
  }

private:
  T find(int a, int b, int k, int l, int r)
  {
    if (r <= a || b <= l)
      return UNIT;
    if (a <= l && r <= b)
      return dat[k];
    T vl = find(a, b, k * 2 + 1, l, (l + r) / 2);
    T vr = find(a, b, k * 2 + 2, (l + r) / 2, r);
    return func(vl, vr);
  }

public:
  T find(int a, int b)
  { // [a, b) の find をする。
    return find(a, b, 0, 0, N);
  }
};

using info = tuple<ll, ll, ll, ll>;
using point = tuple<ll, ll, int>;

int N;
vector<point> V;
vector<info> I;

mint f(info x)
{
  ll a, b, c, d;
  tie(a, b, d, c) = x;
  mint res = 0;
#if DEBUG == 1
  cerr << "(" << a << ", " << b << ", " << c << ", " << d << ")" << endl;
#endif
  res += mint{2}.power(N) - 1;
  res -= mint{2}.power(a + b);
  res -= mint{2}.power(a + c);
  res -= mint{2}.power(b + d);
  res -= mint{2}.power(c + d);
  res += mint{2}.power(a);
  res += mint{2}.power(b);
  res += mint{2}.power(c);
  res += mint{2}.power(d);
#if DEBUG == 1
  cerr << res << endl;
#endif
  return res;
}

int main()
{
  cin >> N;
  set<int> set_x, set_y;
  for (auto i = 0; i < N; i++)
  {
    int x, y;
    cin >> x >> y;
    V.emplace_back(x, y, i);
    set_x.insert(x);
    set_y.insert(y);
  }
  I.resize(N);
  map<int, int> map_x, map_y;
  {
    auto it = set_x.begin();
    for (auto i = 0; i < N; i++)
    {
      map_x[*it] = i;
      ++it;
    }
  }
  {
    auto it = set_y.begin();
    for (auto i = 0; i < N; i++)
    {
      map_y[*it] = i;
      ++it;
    }
  }
  for (auto i = 0; i < N; i++)
  {
    get<0>(V[i]) = map_x[get<0>(V[i])];
    get<1>(V[i]) = map_y[get<0>(V[i])];
  }
  sort(V.begin(), V.end());
  {
    SegTree<ll> tree{N, 0};
    for (auto i = 0; i < N; i++)
    {
      int x, y, ind;
      tie(x, y, ind) = V[i];
      ll k = tree.find(0, y);
      get<0>(I[ind]) = k;
      get<1>(I[ind]) = i - k;
      tree.update(y, 1);
    }
  }
  reverse(V.begin(), V.end());
  {
    SegTree<ll> tree{N, 0};
    for (auto i = 0; i < N; i++)
    {
      int x, y, ind;
      tie(x, y, ind) = V[i];
      ll k = tree.find(0, y);
      get<2>(I[ind]) = k;
      get<3>(I[ind]) = i - k;
      tree.update(y, 1);
    }
  }
  mint ans = 0;
  for (auto i = 0; i < N; i++)
  {
    ans += f(I[i]);
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 12/28/2019, 10:05:50 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // 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} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    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, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &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, const Mint<MOD> &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>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// 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);
}
// ----- main() -----

class Solve
{
  ll N, M, V, P;
  vector<ll> A;
  vector<ll> sum;

public:
  Solve(ll N, ll M, ll V, ll P, vector<ll> A) : N{N}, M{M}, V{V}, P{P}, A(A), sum(N + 1, 0LL)
  {
    sum[P - 1] = A[P - 1];
    for (auto i = P; i < N; i++)
    {
      sum[P] = A[P] + sum[P - 1];
    }
  }

  ll answer()
  {
    if (V <= P)
    {
      return answer0();
    }
    else
    {
      return answer1();
    }
  }

private:
  ll answer0()
  {
    ll ans{0};
    for (auto i = P; i < N; i++)
    {
      if (A[P - 1] <= A[i] + M)
      {
        ans++;
      }
    }
    return ans + P;
  }

  ll answer1()
  {
    ll ok{P - 1};
    ll ng{N};
    if (abs(ok - ng) > 1)
    {
      ll t{(ok + ng) / 2};
#if DEBUG == 1
      cerr << "t = " << t << endl;
#endif
      if (test(t))
      {
        ok = t;
      }
      else
      {
        ng = t;
      }
    }
    return ok + 1;
  }

  bool test(ll i)
  {
    ll K{V - (P - 1) - (N - i)};
    if (K <= 0)
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "A[" << i << "] = " << A[i] << endl;
      cerr << "M = " << M << endl;
      cerr << "P - 1 = " << P - 1 << endl;
      cerr << "A[" << P - 1 << "] = " << A[P - 1] << endl;
#endif
      return A[i] + M >= A[P - 1];
    }
    return (A[i] + M) * (i - (P - 1)) >= sum[i - 1] + K * M;
  }
};

int main()
{
  ll N, M, V, P;
  cin >> N >> M >> V >> P;
  vector<ll> A(N);
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
  }
  sort(A.rbegin(), A.rend());
  Solve solve(N, M, V, P, A);
  cout << solve.answer() << endl;
}
<commit_msg>tried B.cpp to 'B'<commit_after>#define DEBUG 1
/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 12/28/2019, 10:05:50 PM
 * Powered by Visual Studio Code
 */
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
#include <complex>
#include <tuple>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <functional>
#include <random>
#include <chrono>
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
// ----- boost -----
#include <boost/rational.hpp>
// ----- using directives and manipulations -----
using boost::rational;
using namespace std;
using ll = long long;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{1000000007LL};
// constexpr ll MOD{998244353LL}; // be careful
constexpr ll MAX_SIZE{3000010LL};
// constexpr ll MAX_SIZE{30000010LL}; // 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} {}
  Mint operator-() const { return x ? MOD - x : 0; }
  Mint &operator+=(const Mint &a)
  {
    if ((x += a.x) >= MOD)
    {
      x -= MOD;
    }
    return *this;
  }
  Mint &operator-=(const Mint &a) { return *this += -a; }
  Mint &operator*=(const Mint &a)
  {
    (x *= a.x) %= MOD;
    return *this;
  }
  Mint &operator/=(const Mint &a)
  {
    Mint b{a};
    return *this *= b.power(MOD - 2);
  }
  Mint operator+(const Mint &a) const { return Mint(*this) += a; }
  Mint operator-(const Mint &a) const { return Mint(*this) -= a; }
  Mint operator*(const Mint &a) const { return Mint(*this) *= a; }
  Mint operator/(const Mint &a) const { return Mint(*this) /= a; }
  bool operator<(const Mint &a) const { return x < a.x; }
  bool operator<=(const Mint &a) const { return x <= a.x; }
  bool operator>(const Mint &a) const { return x > a.x; }
  bool operator>=(const Mint &a) const { return x >= a.x; }
  bool operator==(const Mint &a) const { return x == a.x; }
  bool operator!=(const Mint &a) const { return !(*this == a); }
  const Mint power(ll N)
  {
    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, const Mint<MOD> &rhs)
{
  return rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs)
{
  return -rhs + lhs;
}
template <ll MOD>
Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs)
{
  return rhs * lhs;
}
template <ll MOD>
Mint<MOD> operator/(ll lhs, const Mint<MOD> &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, const Mint<MOD> &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>;
ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL};
// 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);
}
// ----- main() -----

class Solve
{
  ll N, M, V, P;
  vector<ll> A;
  vector<ll> sum;

public:
  Solve(ll N, ll M, ll V, ll P, vector<ll> A) : N{N}, M{M}, V{V}, P{P}, A(A), sum(N + 1, 0LL)
  {
    sum[P - 1] = A[P - 1];
    for (auto i = P; i < N; i++)
    {
      sum[P] = A[P] + sum[P - 1];
    }
  }

  ll answer()
  {
    if (V <= P)
    {
      return answer0();
    }
    else
    {
      return answer1();
    }
  }

private:
  ll answer0()
  {
    ll ans{0};
    for (auto i = P; i < N; i++)
    {
      if (A[P - 1] <= A[i] + M)
      {
        ans++;
      }
    }
    return ans + P;
  }

  ll answer1()
  {
    ll ok{P - 1};
    ll ng{N};
    while (abs(ok - ng) > 1)
    {
      ll t{(ok + ng) / 2};
#if DEBUG == 1
      cerr << "t = " << t << endl;
#endif
      if (test(t))
      {
        ok = t;
      }
      else
      {
        ng = t;
      }
    }
    return ok + 1;
  }

  bool test(ll i)
  {
    ll K{V - (P - 1) - (N - i)};
    if (K <= 0)
    {
#if DEBUG == 1
      cerr << "i = " << i << endl;
      cerr << "A[" << i << "] = " << A[i] << endl;
      cerr << "M = " << M << endl;
      cerr << "P - 1 = " << P - 1 << endl;
      cerr << "A[" << P - 1 << "] = " << A[P - 1] << endl;
#endif
      return A[i] + M >= A[P - 1];
    }
    return (A[i] + M) * (i - (P - 1)) >= sum[i - 1] + K * M;
  }
};

int main()
{
  ll N, M, V, P;
  cin >> N >> M >> V >> P;
  vector<ll> A(N);
  for (auto i = 0; i < N; i++)
  {
    cin >> A[i];
  }
  sort(A.rbegin(), A.rend());
  Solve solve(N, M, V, P, A);
  cout << solve.answer() << endl;
}
<|endoftext|>