<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_GSLIB
#define MFEM_GSLIB

#include "../config/config.hpp"
#include "gridfunc.hpp"

#ifdef MFEM_USE_GSLIB

struct comm;
struct findpts_data_2;
struct findpts_data_3;
struct array;
struct crystal;

namespace mfem
{

/** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary
 *  collection of points. There are three key functions in FindPointsGSLIB:
 *
 *  1. Setup - constructs the internal data structures of gslib.
 *
 *  2. FindPoints - for any given arbitrary set of points in physical space,
 *     gslib finds the element number, MPI rank, and the reference space
 *     coordinates inside the element that each point is located in. gslib also
 *     returns a code that indicates  wether the point was found inside an
 *     element, on element border, or not found in the domain.
 *
 *  3. Interpolate - Interpolates any gridfunction at the points found using 2.
 *
 *  FindPointsGSLIB provides interface to use these functions individually or using
 *  a single call.
 */
class FindPointsGSLIB
{
protected:
   Mesh *mesh, *meshsplit;
   IntegrationRule *ir_simplex; // IntegrationRule to split quads/hex -> simplex
   struct findpts_data_2 *fdata2D; // pointer to gslib's
   struct findpts_data_3 *fdata3D; // internal data
   int dim, points_cnt;
   Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem;
   Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref;
   bool setupflag;
   struct crystal *cr;
   struct comm *gsl_comm;
   double default_interp_value;

   GridFunction::AvgType avgtype;

   /// Get GridFunction from MFEM format to GSLIB format
   void GetNodeValues(const GridFunction &gf_in, Vector &node_vals);
   /// Get nodal coordinates from mesh to the format expected by GSLIB for quads
   /// and hexes
   void GetQuadHexNodalCoordinates();
   /// Convert simplices to quad/hexes and then get nodal coordinates for each
   /// split element into format expected by GSLIB
   void GetSimplexNodalCoordinates();

   /// Use GSLIB for communication and interpolation
   void InterpolateH1(const GridFunction &field_in, Vector &field_out);
   /// Uses GSLIB Crystal Router for communication followed by MFEM's
   /// interpolation functions
   void InterpolateGeneral(const GridFunction &field_in, Vector &field_out);
   /// Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh
   /// find the original element number (that was split into micro quads/hexes
   /// by GetSimplexNodalCoordinates())
   void MapRefPosAndElemIndices();

public:
   FindPointsGSLIB();

#ifdef MFEM_USE_MPI
   FindPointsGSLIB(MPI_Comm _comm);
#endif

   ~FindPointsGSLIB();

   /** Initializes the internal mesh in gslib, by sending the positions of the
       Gauss-Lobatto nodes of the input Mesh object @a m.
       Note: not tested with periodic (DG meshes).
       Note: the input mesh @a m must have Nodes set.

       @param[in] m         Input mesh.
       @param[in] bb_t      Relative size of bounding box around each element.
       @param[in] newt_tol  Newton tolerance for the gslib search methods.
       @param[in] npt_max   Number of points for simultaneous iteration. This
                            alters performance and memory footprint. */
   void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12,
              const int npt_max = 256);

   /** Searches positions given in physical space by @a point_pos. This function
       populates the following Class variables:
       #point_pos       Positions to be found. Must by ordered by nodes:
                        (XXX...,YYY...,ZZZ).
       #gsl_code        Return codes for each point: inside element (0),
                        element boundary (1), not found (2).
       #gsl_proc        MPI proc ids where the points were found.
       #gsl_elem        Element ids where the points were found.
                        Defaults to 0 for points that were not found.
       #gsl_mfem_elem   Element ids corresponding to MFEM-mesh where the points
                        were found. #gsl_mfem_elem != #gsl_elem for simplices
                        Defaults to 0 for points that were not found.
       #gsl_ref         Reference coordinates of the found point.
                        Ordered by vdim (XYZ,XYZ,XYZ...). Defaults to -1 for
                        points that were not found. Note: the gslib reference
                        frame is [-1,1].
       #gsl_mfem_ref    Reference coordinates #gsl_ref mapped to [0,1].
                        Defaults to 0 for points that were not found.
       #gsl_dist        Distance between the sought and the found point
                        in physical space. */
   void FindPoints(const Vector &point_pos);
   /// Setup FindPoints and search positions
   void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1,
                   const double newt_tol = 1.0e-12,  const int npt_max = 256);

   /** Interpolation of field values at prescribed reference space positions.
       @param[in] field_in    Function values that will be interpolated on the
                              reference positions. Note: it is assumed that
                              @a field_in is in H1 and in the same space as the
                              mesh that was given to Setup().
       @param[out] field_out  Interpolated values. For points that are not found
                              the value is set to #default_interp_value. */
   void Interpolate(const GridFunction &field_in, Vector &field_out);
   /** Search positions and interpolate */
   void Interpolate(const Vector &point_pos, const GridFunction &field_in,
                    Vector &field_out);
   /** Setup FindPoints, search positions and interpolate */
   void Interpolate(Mesh &m, const Vector &point_pos,
                    const GridFunction &field_in, Vector &field_out);

   /// Average type to be used for L2 functions in-case a point is located at
   /// an element boundary where the function might not have a unique value.
   void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; }

   /// Set the default interpolation value for points that are not found in the
   /// mesh.
   void SetDefaultInterpolationValue(double interp_value_)
   {
      default_interp_value = interp_value_;
   }

   /** Cleans up memory allocated internally by gslib.
       Note that in parallel, this must be called before MPI_Finalize(), as
       it calls MPI_Comm_free() for internal gslib communicators. */
   void FreeData();

   /// Return code for each point searched by FindPoints: inside element (0), on
   /// element boundary (1), or not found (2).
   const Array<unsigned int> &GetCode() const { return gsl_code; }
   /// Return element number for each point found by FindPoints.
   const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; }
   /// Return MPI rank on which each point was found by FindPoints.
   const Array<unsigned int> &GetProc() const { return gsl_proc; }
   /// Return reference coordinates for each point found by FindPoints.
   const Vector &GetReferencePosition() const { return gsl_mfem_ref;  }
   /// Return distance Distance between the sought and the found point
   /// in physical space, for each point found by FindPoints.
   const Vector &GetDist()              const { return gsl_dist; }

   /// Return element number for each point found by FindPoints corresponding to
   /// GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices.
   const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; }
   /// Return reference coordinates in [-1,1] (internal range in GSLIB) for each
   /// point found by FindPoints.
   const Vector &GetGSLIBReferencePosition() const { return gsl_ref; }
};

} // namespace mfem

#endif //MFEM_USE_GSLIB

#endif //MFEM_GSLIB guard
<commit_msg>minor<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.

#ifndef MFEM_GSLIB
#define MFEM_GSLIB

#include "../config/config.hpp"
#include "gridfunc.hpp"

#ifdef MFEM_USE_GSLIB

struct comm;
struct findpts_data_2;
struct findpts_data_3;
struct array;
struct crystal;

namespace mfem
{

/** \brief FindPointsGSLIB can robustly evaluate a GridFunction on an arbitrary
 *  collection of points. There are three key functions in FindPointsGSLIB:
 *
 *  1. Setup - constructs the internal data structures of gslib.
 *
 *  2. FindPoints - for any given arbitrary set of points in physical space,
 *     gslib finds the element number, MPI rank, and the reference space
 *     coordinates inside the element that each point is located in. gslib also
 *     returns a code that indicates  wether the point was found inside an
 *     element, on element border, or not found in the domain.
 *
 *  3. Interpolate - Interpolates any gridfunction at the points found using 2.
 *
 *  FindPointsGSLIB provides interface to use these functions individually or using
 *  a single call.
 */
class FindPointsGSLIB
{
protected:
   Mesh *mesh, *meshsplit;
   IntegrationRule *ir_simplex; // IntegrationRule to split quads/hex -> simplex
   struct findpts_data_2 *fdata2D; // pointer to gslib's
   struct findpts_data_3 *fdata3D; // internal data
   int dim, points_cnt;
   Array<unsigned int> gsl_code, gsl_proc, gsl_elem, gsl_mfem_elem;
   Vector gsl_mesh, gsl_ref, gsl_dist, gsl_mfem_ref;
   bool setupflag;
   struct crystal *cr;
   struct comm *gsl_comm;
   double default_interp_value;

   GridFunction::AvgType avgtype;

   /// Get GridFunction from MFEM format to GSLIB format
   void GetNodeValues(const GridFunction &gf_in, Vector &node_vals);
   /// Get nodal coordinates from mesh to the format expected by GSLIB for quads
   /// and hexes
   void GetQuadHexNodalCoordinates();
   /// Convert simplices to quad/hexes and then get nodal coordinates for each
   /// split element into format expected by GSLIB
   void GetSimplexNodalCoordinates();

   /// Use GSLIB for communication and interpolation
   void InterpolateH1(const GridFunction &field_in, Vector &field_out);
   /// Uses GSLIB Crystal Router for communication followed by MFEM's
   /// interpolation functions
   void InterpolateGeneral(const GridFunction &field_in, Vector &field_out);
   /// Map {r,s,t} coordinates from [-1,1] to [0,1] for MFEM. For simplices mesh
   /// find the original element number (that was split into micro quads/hexes
   /// by GetSimplexNodalCoordinates())
   void MapRefPosAndElemIndices();

public:
   FindPointsGSLIB();

#ifdef MFEM_USE_MPI
   FindPointsGSLIB(MPI_Comm _comm);
#endif

   ~FindPointsGSLIB();

   /** Initializes the internal mesh in gslib, by sending the positions of the
       Gauss-Lobatto nodes of the input Mesh object @a m.
       Note: not tested with periodic (DG meshes).
       Note: the input mesh @a m must have Nodes set.

       @param[in] m         Input mesh.
       @param[in] bb_t      Relative size of bounding box around each element.
       @param[in] newt_tol  Newton tolerance for the gslib search methods.
       @param[in] npt_max   Number of points for simultaneous iteration. This
                            alters performance and memory footprint. */
   void Setup(Mesh &m, const double bb_t = 0.1, const double newt_tol = 1.0e-12,
              const int npt_max = 256);

   /** Searches positions given in physical space by @a point_pos. These positions
       must by ordered by nodes: (XXX...,YYY...,ZZZ).
       This function populates the following member variables:
       #gsl_code        Return codes for each point: inside element (0),
                        element boundary (1), not found (2).
       #gsl_proc        MPI proc ids where the points were found.
       #gsl_elem        Element ids where the points were found.
                        Defaults to 0 for points that were not found.
       #gsl_mfem_elem   Element ids corresponding to MFEM-mesh where the points
                        were found. #gsl_mfem_elem != #gsl_elem for simplices
                        Defaults to 0 for points that were not found.
       #gsl_ref         Reference coordinates of the found point.
                        Ordered by vdim (XYZ,XYZ,XYZ...). Defaults to -1 for
                        points that were not found. Note: the gslib reference
                        frame is [-1,1].
       #gsl_mfem_ref    Reference coordinates #gsl_ref mapped to [0,1].
                        Defaults to 0 for points that were not found.
       #gsl_dist        Distance between the sought and the found point
                        in physical space. */
   void FindPoints(const Vector &point_pos);
   /// Setup FindPoints and search positions
   void FindPoints(Mesh &m, const Vector &point_pos, const double bb_t = 0.1,
                   const double newt_tol = 1.0e-12,  const int npt_max = 256);

   /** Interpolation of field values at prescribed reference space positions.
       @param[in] field_in    Function values that will be interpolated on the
                              reference positions. Note: it is assumed that
                              @a field_in is in H1 and in the same space as the
                              mesh that was given to Setup().
       @param[out] field_out  Interpolated values. For points that are not found
                              the value is set to #default_interp_value. */
   void Interpolate(const GridFunction &field_in, Vector &field_out);
   /** Search positions and interpolate */
   void Interpolate(const Vector &point_pos, const GridFunction &field_in,
                    Vector &field_out);
   /** Setup FindPoints, search positions and interpolate */
   void Interpolate(Mesh &m, const Vector &point_pos,
                    const GridFunction &field_in, Vector &field_out);

   /// Average type to be used for L2 functions in-case a point is located at
   /// an element boundary where the function might not have a unique value.
   void SetL2AvgType(GridFunction::AvgType avgtype_) { avgtype = avgtype_; }

   /// Set the default interpolation value for points that are not found in the
   /// mesh.
   void SetDefaultInterpolationValue(double interp_value_)
   {
      default_interp_value = interp_value_;
   }

   /** Cleans up memory allocated internally by gslib.
       Note that in parallel, this must be called before MPI_Finalize(), as
       it calls MPI_Comm_free() for internal gslib communicators. */
   void FreeData();

   /// Return code for each point searched by FindPoints: inside element (0), on
   /// element boundary (1), or not found (2).
   const Array<unsigned int> &GetCode() const { return gsl_code; }
   /// Return element number for each point found by FindPoints.
   const Array<unsigned int> &GetElem() const { return gsl_mfem_elem; }
   /// Return MPI rank on which each point was found by FindPoints.
   const Array<unsigned int> &GetProc() const { return gsl_proc; }
   /// Return reference coordinates for each point found by FindPoints.
   const Vector &GetReferencePosition() const { return gsl_mfem_ref;  }
   /// Return distance Distance between the sought and the found point
   /// in physical space, for each point found by FindPoints.
   const Vector &GetDist()              const { return gsl_dist; }

   /// Return element number for each point found by FindPoints corresponding to
   /// GSLIB mesh. gsl_mfem_elem != gsl_elem for mesh with simplices.
   const Array<unsigned int> &GetGSLIBElem() const { return gsl_elem; }
   /// Return reference coordinates in [-1,1] (internal range in GSLIB) for each
   /// point found by FindPoints.
   const Vector &GetGSLIBReferencePosition() const { return gsl_ref; }
};

} // namespace mfem

#endif //MFEM_USE_GSLIB

#endif //MFEM_GSLIB guard
<|endoftext|>


<commit_before>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "SkBenchmark.h"
#include "SkBlurMask.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkColorFilter.h"
#include "SkLayerDrawLooper.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRect.h"
#include "SkRRect.h"
#include "SkString.h"
#include "SkXfermode.h"

class BlurRoundRectBench : public SkBenchmark {
public:
    BlurRoundRectBench(int width, int height,
                       // X and Y radii for the upper left corner
                       int ulX, int ulY,
                       // X and Y radii for the upper right corner
                       int urX, int urY,
                       // X and Y radii for the lower right corner
                       int lrX, int lrY,
                       // X and Y radii for the lower left corner
                       int llX, int llY)
        : fName("blurroundrect")
        , fWidth(width)
        , fHeight(height) {
        fName.appendf("_WH[%ix%i]_UL[%ix%i]_UR[%ix%i]_LR[%ix%i]_LL[%ix%i]",
                      width, height,
                      ulX,   ulY,
                      urX,   urY,
                      lrX,   lrY,
                      llX,   llY);
        fRadii[0].set(SkIntToScalar(ulX), SkIntToScalar(ulY));
        fRadii[1].set(SkIntToScalar(urX), SkIntToScalar(urY));
        fRadii[2].set(SkIntToScalar(lrX), SkIntToScalar(lrY));
        fRadii[3].set(SkIntToScalar(llX), SkIntToScalar(llY));
    }

    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();
    }

    virtual SkIPoint onGetSize() SK_OVERRIDE {
        return SkIPoint::Make(fWidth, fHeight);
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        for (int i = 0; i < this->getLoops(); i++) {
            SkLayerDrawLooper* looper = new SkLayerDrawLooper;
            {
                SkLayerDrawLooper::LayerInfo info;
                info.fFlagsMask = 0;
                info.fPaintBits = 40;
                info.fColorMode = SkXfermode::kSrc_Mode;
                info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0));
                info.fPostTranslate = false;
                SkPaint* paint = looper->addLayerOnTop(info);
                SkMaskFilter* maskFilter = SkBlurMaskFilter::Create(SK_ScalarHalf,
                        SkBlurMaskFilter::kNormal_BlurStyle,
                        SkBlurMaskFilter::kHighQuality_BlurFlag);
                paint->setMaskFilter(maskFilter)->unref();
                SkColorFilter* colorFilter = SkColorFilter::CreateModeFilter(SK_ColorLTGRAY,
                        SkXfermode::kSrcIn_Mode);
                paint->setColorFilter(colorFilter)->unref();
                paint->setColor(SK_ColorGRAY);
            }
            {
                SkLayerDrawLooper::LayerInfo info;
                looper->addLayerOnTop(info);
            }
            SkPaint paint;
            SkRect rect = SkRect::MakeWH(fWidth, fHeight);
            canvas->drawRect(rect, paint);

            paint.setLooper(looper)->unref();
            paint.setAntiAlias(true);
            paint.setColor(SK_ColorCYAN);

            SkRRect rrect;
            rrect.setRectRadii(rect, fRadii);
            canvas->drawRRect(rrect, paint);
        }
    }

private:
    SkString fName;
    const int fWidth;
    const int fHeight;
    SkVector fRadii[4];
    typedef SkBenchmark INHERITED;
};

// Create one with dimensions/rounded corners based on the skp
DEF_BENCH(return new BlurRoundRectBench(600, 5514, 6, 6, 6, 6, 6, 6, 6, 6);)
// Same radii, much smaller rectangle
DEF_BENCH(return new BlurRoundRectBench(100, 100, 6, 6, 6, 6, 6, 6, 6, 6);)
// Rounded rect with two opposite corners with large radii, the other two
// small.
DEF_BENCH(return new BlurRoundRectBench(100, 100, 30, 30, 10, 10, 30, 30, 10, 10);)
DEF_BENCH(return new BlurRoundRectBench(100, 100, 90, 90, 90, 90, 90, 90, 90, 90);)
<commit_msg>Another int to scalar fix.<commit_after>/*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/

#include "SkBenchmark.h"
#include "SkBlurMask.h"
#include "SkBlurMaskFilter.h"
#include "SkCanvas.h"
#include "SkColorFilter.h"
#include "SkLayerDrawLooper.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkPoint.h"
#include "SkRect.h"
#include "SkRRect.h"
#include "SkString.h"
#include "SkXfermode.h"

class BlurRoundRectBench : public SkBenchmark {
public:
    BlurRoundRectBench(int width, int height,
                       // X and Y radii for the upper left corner
                       int ulX, int ulY,
                       // X and Y radii for the upper right corner
                       int urX, int urY,
                       // X and Y radii for the lower right corner
                       int lrX, int lrY,
                       // X and Y radii for the lower left corner
                       int llX, int llY)
        : fName("blurroundrect")
        , fWidth(width)
        , fHeight(height) {
        fName.appendf("_WH[%ix%i]_UL[%ix%i]_UR[%ix%i]_LR[%ix%i]_LL[%ix%i]",
                      width, height,
                      ulX,   ulY,
                      urX,   urY,
                      lrX,   lrY,
                      llX,   llY);
        fRadii[0].set(SkIntToScalar(ulX), SkIntToScalar(ulY));
        fRadii[1].set(SkIntToScalar(urX), SkIntToScalar(urY));
        fRadii[2].set(SkIntToScalar(lrX), SkIntToScalar(lrY));
        fRadii[3].set(SkIntToScalar(llX), SkIntToScalar(llY));
    }

    virtual const char* onGetName() SK_OVERRIDE {
        return fName.c_str();
    }

    virtual SkIPoint onGetSize() SK_OVERRIDE {
        return SkIPoint::Make(fWidth, fHeight);
    }

    virtual void onDraw(SkCanvas* canvas) SK_OVERRIDE {
        for (int i = 0; i < this->getLoops(); i++) {
            SkLayerDrawLooper* looper = new SkLayerDrawLooper;
            {
                SkLayerDrawLooper::LayerInfo info;
                info.fFlagsMask = 0;
                info.fPaintBits = 40;
                info.fColorMode = SkXfermode::kSrc_Mode;
                info.fOffset = SkPoint::Make(SkIntToScalar(-1), SkIntToScalar(0));
                info.fPostTranslate = false;
                SkPaint* paint = looper->addLayerOnTop(info);
                SkMaskFilter* maskFilter = SkBlurMaskFilter::Create(SK_ScalarHalf,
                        SkBlurMaskFilter::kNormal_BlurStyle,
                        SkBlurMaskFilter::kHighQuality_BlurFlag);
                paint->setMaskFilter(maskFilter)->unref();
                SkColorFilter* colorFilter = SkColorFilter::CreateModeFilter(SK_ColorLTGRAY,
                        SkXfermode::kSrcIn_Mode);
                paint->setColorFilter(colorFilter)->unref();
                paint->setColor(SK_ColorGRAY);
            }
            {
                SkLayerDrawLooper::LayerInfo info;
                looper->addLayerOnTop(info);
            }
            SkPaint paint;
            SkRect rect = SkRect::MakeWH(SkIntToScalar(fWidth), SkIntToScalar(fHeight));
            canvas->drawRect(rect, paint);

            paint.setLooper(looper)->unref();
            paint.setAntiAlias(true);
            paint.setColor(SK_ColorCYAN);

            SkRRect rrect;
            rrect.setRectRadii(rect, fRadii);
            canvas->drawRRect(rrect, paint);
        }
    }

private:
    SkString fName;
    const int fWidth;
    const int fHeight;
    SkVector fRadii[4];
    typedef SkBenchmark INHERITED;
};

// Create one with dimensions/rounded corners based on the skp
DEF_BENCH(return new BlurRoundRectBench(600, 5514, 6, 6, 6, 6, 6, 6, 6, 6);)
// Same radii, much smaller rectangle
DEF_BENCH(return new BlurRoundRectBench(100, 100, 6, 6, 6, 6, 6, 6, 6, 6);)
// Rounded rect with two opposite corners with large radii, the other two
// small.
DEF_BENCH(return new BlurRoundRectBench(100, 100, 30, 30, 10, 10, 30, 30, 10, 10);)
DEF_BENCH(return new BlurRoundRectBench(100, 100, 90, 90, 90, 90, 90, 90, 90, 90);)
<|endoftext|>


<commit_before>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 21:10:12
 * 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 <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 1 // change 0 -> 1 if we need debug.

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;

ll A, B;

int solve()
{
  ll S = A * B;
  if (A > B)
    swap(A, B);
  if (S <= 2)
    return 0;
  ll ub = S;
  ll lb = 1;
  while (ub - lb > 1)
  {
    ll t = (ub + lb) / 2;
    if ((S+t)/(t+1) + 1 >= (S+t-1)/t)
    {
      ub = t;
    }
    else
    {
      lb = t;
    }
  }
#if DEBUG == 1
  cerr << "S = " << S << ", ub = " << ub << endl;
#endif
  ll ans = (ub - 1) + ((S+ub-1) / ub - 1);
  ll X = ub - 1;
  ll Y = (S + ub - 1) / ub - 1;
  if (X > Y)
    swap(X, Y);
  if (B <= X)
  {
    ans -= 2;
  }
  else if (A > Y)
  {
    //
  }
  else
  {
    ans -= 1;
  }
  return ans;
}

int main()
{
  int Q;
  cin >> Q;
  for (auto i = 0; i < Q; i++)
  {
    cin >> A >> B;
    cout << solve() << endl;
  }
}<commit_msg>tried D.cpp to 'D'<commit_after>/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-7 21:10:12
 * 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 <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 1 // change 0 -> 1 if we need debug.

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;

ll A, B;

int solve()
{
  ll S = A * B;
  if (A > B)
    swap(A, B);
  if (S <= 2)
    return 0;
  ll ub = S;
  ll lb = 1;
  while (ub - lb > 1)
  {
    ll t = (ub + lb) / 2;
    if ((S+t)/(t+1) >= (S+t-1)/t)
    {
      ub = t;
    }
    else
    {
      lb = t;
    }
  }
#if DEBUG == 1
  cerr << "S = " << S << ", ub = " << ub << endl;
#endif
  ll ans = (ub - 1) + ((S+ub-1) / ub - 1);
  ll X = ub - 1;
  ll Y = (S + ub - 1) / ub - 1;
  if (X > Y)
    swap(X, Y);
  if (B <= X)
  {
    ans -= 2;
  }
  else if (A > Y)
  {
    //
  }
  else
  {
    ans -= 1;
  }
  return ans;
}

int main()
{
  int Q;
  cin >> Q;
  for (auto i = 0; i < Q; i++)
  {
    cin >> A >> B;
    cout << solve() << endl;
  }
}<|endoftext|>


<commit_before>/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-15 23:25:04
 * 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 <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

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, M, Q;
int a[50];
int l[50];
int r[50];
bool used[50];

ll solve()
{
  ll ans = 0;
  for (auto i = 0; i < Q; i++)
  {
    int maxi = 0;
    for (auto j = l[i]; j <= r[i]; j++)
    {
      if (!used[j] && a[j] > maxi)
      {
        maxi = a[j];
      }
    }
    // cerr << maxi << " ";
    ans += maxi;
  }
  // cerr << ", ans = " << ans << endl;
  return ans;
}

void solveA()
{
  ll ans = 100000000;
  for (auto i = 0; i < (1 << N); i++)
  {
    int cnt = 0;
    for (auto j = 0; j < N; j++)
    {
      if ((i >> j) & 1)
      {
        cnt++;
      }
    }
    if (cnt == M)
    {
      for (auto j = 0; j < N; j++)
      {
        used[j] = (i >> j) & 1;
      }
      ans = min(ans, solve());
    }
  }
  cout << ans << endl;
}

void solveB()
{
  fill(used, used + N, false);
  int c[50];
  fill(c, c + 50, 0);
  for (auto i = 0; i < Q; i++)
  {
    for (auto j = l[i]; j <= r[i]; j++)
    {
      c[j]++;
    }
  }
  vector< tuple<int, int> > V;
  for (auto i = 0; i < N; i++)
  {
    V.push_back(make_tuple(c[i], i));
  }
  sort(V.begin(), V.end());
  reverse(V.begin(), V.end());
  for (auto i = 0; i < M; i++)
  {
    used[get<1>(V[i])] = true;
  }
  cout << solve() << endl;
}

int main()
{
  cin >> N >> M >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  for (auto i = 0; i < Q; i++)
  {
    cin >> l[i] >> r[i];
    l[i]--;
    r[i]--;
  }
  if (N <= 15)
  {
    solveA();
  }
  else
  {
    solveB();
  }
}<commit_msg>submit F.cpp to 'F - Lunch Menu' (s8pc-5) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : F.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-4-15 23:25:04
 * 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 <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;

#define DEBUG 0 // change 0 -> 1 if we need debug.

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, M, Q;
int a[50];
int l[50];
int r[50];
bool used[50];

ll solve()
{
  ll ans = 0;
  for (auto i = 0; i < Q; i++)
  {
    int maxi = 0;
    for (auto j = l[i]; j <= r[i]; j++)
    {
      if (!used[j] && a[j] > maxi)
      {
        maxi = a[j];
      }
    }
    // cerr << maxi << " ";
    ans += maxi;
  }
  // cerr << ", ans = " << ans << endl;
  return ans;
}

void solveA()
{
  ll ans = 10000000000000;
  for (auto i = 0; i < (1 << N); i++)
  {
    int cnt = 0;
    for (auto j = 0; j < N; j++)
    {
      if ((i >> j) & 1)
      {
        cnt++;
      }
    }
    if (cnt == M)
    {
      for (auto j = 0; j < N; j++)
      {
        used[j] = (i >> j) & 1;
      }
      ans = min(ans, solve());
    }
  }
  cout << ans << endl;
}

void solveB()
{
  fill(used, used + N, false);
  int c[50];
  fill(c, c + 50, 0);
  for (auto i = 0; i < Q; i++)
  {
    for (auto j = l[i]; j <= r[i]; j++)
    {
      c[j]++;
    }
  }
  vector< tuple<int, int> > V;
  for (auto i = 0; i < N; i++)
  {
    V.push_back(make_tuple(c[i], i));
  }
  sort(V.begin(), V.end());
  reverse(V.begin(), V.end());
  for (auto i = 0; i < M; i++)
  {
    used[get<1>(V[i])] = true;
  }
  cout << solve() << endl;
}

int main()
{
  cin >> N >> M >> Q;
  for (auto i = 0; i < N; i++)
  {
    cin >> a[i];
  }
  for (auto i = 0; i < Q; i++)
  {
    cin >> l[i] >> r[i];
    l[i]--;
    r[i]--;
  }
  if (N <= 15)
  {
    solveA();
  }
  else
  {
    solveB();
  }
}<|endoftext|>


<commit_before>/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-3 21:04:40
 * 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 <random> // random_device rd; mt19937 mt(rd());
#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;

#define DEBUG 0 // change 0 -> 1 if we need debug.

const int MAX_SIZE = 1000010;
const long long MOD = 998244353;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

typedef long long ll;

void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = (i * fact[i - 1]) % MOD;
    factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
  }
}

long long C(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
  }
  return 0;
}

long long power(long long x, long long n)
{
  if (n == 0)
  {
    return 1;
  }
  else if (n % 2 == 1)
  {
    return (x * power(x, n - 1)) % MOD;
  }
  else
  {
    long long half = power(x, n / 2);
    return (half * half) % MOD;
  }
}

long long gcm(long long a, long long b)
{
  if (a < b)
  {
    return gcm(b, a);
  }
  if (b == 0)
    return a;
  return gcm(b, a % b);
}

ll N, A, B, K;

ll calc(ll k, ll l)
{
  return (C(N, k) * C(N, l)) % MOD;
}

int main()
{
  cin >> N >> A >> B >> K;
  ll g = gcm(A, B);
  if (K % g != 0)
  {
    cout << 0 << endl;
    return 0;
  }
  A /= g;
  B /= g;
  K /= g;
  ll ans = 0;
  for (ll k = 0; k <= N; k++)
  {
    ll BL = K - A * k;
    if (BL % B == 0)
    {
      ll l = BL / B;
      if (0 <= l && l <= N)
      {
        ans += calc(k, l);
        ans %= MOD;
      }
    }
  }
  cout << ans << endl;
}<commit_msg>submit B.cpp to 'B - RGB Coloring' (agc025) [C++14 (GCC 5.4.1)]<commit_after>/**
 * File    : B.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-6-3 21:04:40
 * 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 <random> // random_device rd; mt19937 mt(rd());
#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;

#define DEBUG 0 // change 0 -> 1 if we need debug.

const int MAX_SIZE = 1000010;
const long long MOD = 998244353;

long long inv[MAX_SIZE];
long long fact[MAX_SIZE];
long long factinv[MAX_SIZE];

typedef long long ll;

void init()
{
  inv[1] = 1;
  for (int i = 2; i < MAX_SIZE; i++)
  {
    inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD;
  }
  fact[0] = factinv[0] = 1;
  for (int i = 1; i < MAX_SIZE; i++)
  {
    fact[i] = (i * fact[i - 1]) % MOD;
    factinv[i] = (inv[i] * factinv[i - 1]) % MOD;
  }
}

long long C(int n, int k)
{
  if (n >= 0 && k >= 0 && n - k >= 0)
  {
    return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD;
  }
  return 0;
}

long long power(long long x, long long n)
{
  if (n == 0)
  {
    return 1;
  }
  else if (n % 2 == 1)
  {
    return (x * power(x, n - 1)) % MOD;
  }
  else
  {
    long long half = power(x, n / 2);
    return (half * half) % MOD;
  }
}

long long gcm(long long a, long long b)
{
  if (a < b)
  {
    return gcm(b, a);
  }
  if (b == 0)
    return a;
  return gcm(b, a % b);
}

ll N, A, B, K;

ll calc(ll k, ll l)
{
  return (C(N, k) * C(N, l)) % MOD;
}

int main()
{
  init();
  cin >> N >> A >> B >> K;
  ll g = gcm(A, B);
  if (K % g != 0)
  {
    cout << 0 << endl;
    return 0;
  }
  A /= g;
  B /= g;
  K /= g;
  ll ans = 0;
  for (ll k = 0; k <= N; k++)
  {
    ll BL = K - A * k;
    if (BL % B == 0)
    {
      ll l = BL / B;
      if (0 <= l && l <= N)
      {
        ans += calc(k, l);
        ans %= MOD;
      }
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-8-25 20:45:21
 * 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(19920725));
#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;

#define DEBUG 0 // change 0 -> 1 if we need debug.

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, K;
ll x[100010];
vector<ll> V[2];

int main()
{
  cin >> N >> K;
  for (auto i = 0; i < N; i++)
  {
    cin >> x[i];
  }
  for (auto i = 0; i < N; i++)
  {
    if (x[i] > 0)
    {
      V[0].push_back(x[i]);
    }
    else
    {
      V[1].push_back(-x[i]);
    }
  }
  sort(V[1].begin(), V[1].end());
  ll ans = 100000000000000;
  for (auto i = 0; i < 2; i++)
  {
    if ((int)V[i].size() >= K)
    {
      ans = min(ans, V[i][K - 1]);
    }
  }
  for (auto k = 0; k <= K; k++)
  {
    int l = K - k;
    if ((int)V[0].size() >= k && l >= 0 && (int)V[1].size() >= l)
    {
      ans = min(ans, V[0][k - 1] + 2 * V[1][l - 1]);
      ans = min(ans, 2 * V[0][k - 1] + V[1][l - 1]);
    }
  }
  cout << ans << endl;
}<commit_msg>tried C.cpp to 'C'<commit_after>/**
 * File    : C.cpp
 * Author  : Kazune Takahashi
 * Created : 2018-8-25 20:45:21
 * 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(19920725));
#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;

#define DEBUG 0 // change 0 -> 1 if we need debug.

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, K;
ll x[100010];
vector<ll> V[2];

int main()
{
  cin >> N >> K;
  for (auto i = 0; i < N; i++)
  {
    cin >> x[i];
  }
  for (auto i = 0; i < N; i++)
  {
    if (x[i] > 0)
    {
      V[0].push_back(x[i]);
    }
    else
    {
      V[1].push_back(-1 * x[i]);
    }
  }
  sort(V[1].begin(), V[1].end());
  for (auto x : V[0])
  {
    cerr << x << endl;
  }
  cerr << " " << endl;
  for (auto x : V[1])
  {
    cerr << x << endl;
  }
  ll ans = 100000000000000;
  for (auto i = 0; i < 2; i++)
  {
    if ((int)V[i].size() >= K)
    {
      ans = min(ans, V[i][K - 1]);
    }
  }
  for (auto k = 0; k <= K; k++)
  {
    int l = K - k;
    if ((int)V[0].size() >= k && (int)V[1].size() >= l)
    {
      ans = min(ans, V[0][k - 1] + 2 * V[1][l - 1]);
      ans = min(ans, 2 * V[0][k - 1] + V[1][l - 1]);
    }
  }
  cout << ans << endl;
}<|endoftext|>


<commit_before>#define DEBUG 1

/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 3/9/2019, 9:11:28 PM
 * 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;

ll A, B;

ll X(ll L)
{
  ll ans = 0;
  for (auto i = 0; i < 60; i++)
  {
    ll M = (1LL << (i + 1));
    ll cnt = L % M;
#if DEBUG == 1
    cerr << "M = " << M << ", cnt = " << cnt << endl;
#endif
    if (cnt >= M / 2)
    {
      cnt -= M / 2;
      if (cnt % 2 == 1)
      {
        ans += (1LL << i);
      }
    }
  }
  return ans;
}

int main()
{
  cin >> A >> B;
  cout << (X(A) ^ X(B)) << endl;
}<commit_msg>tried D.cpp to 'D'<commit_after>#define DEBUG 1

/**
 * File    : D.cpp
 * Author  : Kazune Takahashi
 * Created : 3/9/2019, 9:11:28 PM
 * 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;

ll A, B;

ll X(ll L)
{
  ll ans = 0;
  for (auto i = 0; i < 60; i++)
  {
    ll M = (1LL << (i + 1));
    ll cnt = L % M;
#if DEBUG == 1
    cerr << "M = " << M << ", cnt = " << cnt << endl;
#endif
    if (cnt >= M / 2)
    {
      cnt -= M / 2;
      if (cnt % 2 == 1)
      {
        ans += (1LL << i);
      }
    }
#if DEBUG == 1
    cerr << "ans = " << ans << endl;
#endif
  }
  return ans;
}

int main()
{
  cin >> A >> B;
  cout << (X(A) ^ X(B)) << endl;
}<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 11/18/2019, 8:58:07 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{3000010LL}; // 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; }
  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() -----

void add_edge(map<int, int> &m, int h, int d)
{
  if (m.find(h) == m.end())
  {
    m[h] = d;
  }
  else
  {
    ch_max(m[h], d);
  }
}

void calc_high(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)
{
  add_edge(M[i + 1], A[i + 1] - (A[i] - h), d);
  add_edge(M[i + 1], h, d + 1);
  add_edge(M[i + 1], 0, d + 2);
}

void calc_low(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)
{
  if (h <= A[i + 1])
  {
    add_edge(M[i + 1], h, d);
  }
  add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1);
  add_edge(M[i + 1], 0, d + 2);
}

void eliminate(map<int, int> &m)
{
  int now{m[0]};
  map<int, int> k;
  for (auto const &x : m)
  {
    if (x.second == now)
    {
      k.insert(x);
      --now;
    }
  }
  swap(m, k);
}

void calc(vector<int> const &A, vector<map<int, int>> &M, int i, pair<int, int> const &x)
{
  int h{x.first};
  int d{x.second};
  if (A[i] <= A[i + 1])
  {
    calc_high(A, M, i, h, d);
  }
  else
  {
    calc_low(A, M, i, h, d);
  }
#if DEBUG == 1
  for (auto const &x : M[i + 1])
  {
    cerr << "M[" << i + 1 << "][" << x.first << "] = " << x.second << endl;
  }
#endif
  eliminate(M[i + 1]);
}

int main()
{
  int N;
  cin >> N;
  vector<int> A(N + 1, 0);
  for (auto i = 1; i <= N; i++)
  {
    cin >> A[i];
  }
  vector<map<int, int>> M(N + 1);
  M[0][0] = 0;
  for (auto i = 0; i < N; i++)
  {
    for (auto const &x : M[i])
    {
      calc(A, M, i, x);
    }
  }
  cout << M[N].end()->second << endl;
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 11/18/2019, 8:58:07 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{3000010LL}; // 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; }
  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() -----

void add_edge(map<int, int> &m, int h, int d)
{
  if (m.find(h) == m.end())
  {
    m[h] = d;
  }
  else
  {
    ch_min(m[h], d);
  }
}

void calc_high(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)
{
  add_edge(M[i + 1], A[i + 1] - (A[i] - h), d);
  add_edge(M[i + 1], h, d + 1);
  add_edge(M[i + 1], 0, d + 2);
}

void calc_low(vector<int> const &A, vector<map<int, int>> &M, int i, int h, int d)
{
  if (h <= A[i + 1])
  {
    add_edge(M[i + 1], h, d);
  }
  add_edge(M[i + 1], max(0, A[i + 1] - (A[i] - h)), d + 1);
  add_edge(M[i + 1], 0, d + 2);
}

void eliminate(map<int, int> &m)
{
  int now{m[0]};
  map<int, int> k;
  for (auto const &x : m)
  {
    if (x.second == now)
    {
      k.insert(x);
      --now;
    }
  }
  swap(m, k);
}

void calc(vector<int> const &A, vector<map<int, int>> &M, int i, pair<int, int> const &x)
{
  int h{x.first};
  int d{x.second};
  if (A[i] <= A[i + 1])
  {
    calc_high(A, M, i, h, d);
  }
  else
  {
    calc_low(A, M, i, h, d);
  }
#if DEBUG == 1
  for (auto const &x : M[i + 1])
  {
    cerr << "M[" << i + 1 << "][" << x.first << "] = " << x.second << endl;
  }
#endif
  eliminate(M[i + 1]);
}

int main()
{
  int N;
  cin >> N;
  vector<int> A(N + 1, 0);
  for (auto i = 1; i <= N; i++)
  {
    cin >> A[i];
  }
  vector<map<int, int>> M(N + 1);
  M[0][0] = 0;
  for (auto i = 0; i < N; i++)
  {
    for (auto const &x : M[i])
    {
      calc(A, M, i, x);
    }
  }
  cout << M[N].end()->second << endl;
}
<|endoftext|>


<commit_before>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 4/23/2020, 7:08:47 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{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 + MOD) % 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++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(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>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Point -----

using Point = tuple<int, int>;

ostream &operator<<(ostream &os, Point const &pt)
{
  return os << get<0>(pt) << " " << get<1>(pt);
}

// ----- Cycle -----

class Cycle
{
  int num;
  bool pos;

public:
  Cycle(int num, bool pos) : num{num}, pos{pos} {}

  vector<Point> path() const
  {
    vector<Point> ans;
    for (auto i = 0; i <= num; ++i)
    {
      ans.push_back(Point(i, 0));
    }
    if (pos)
    {
      ans.push_back(Point(num + 1, 0));
      ans.push_back(Point(num + 1, 1));
      ans.push_back(Point(num, 1));
    }
    else
    {
      ans.push_back(Point(num, 1));
      ans.push_back(Point(num + 1, 1));
      ans.push_back(Point(num + 1, 0));
    }
    for (auto i = num; i >= 1; --i)
    {
      ans.push_back(Point(i, 0));
    }
    return ans;
  }

  Cycle inv() const
  {
    return Cycle(num, !pos);
  }
};

class Chain
{
  vector<Cycle> V;

public:
  Chain() {}
  Chain(Cycle c) : V{c} {}
  Chain(vector<Cycle> V) : V(V) {}

  Chain(int mask)
  {
#if DEBUG == 1
    cerr << "mask = " << mask << endl;
#endif
    int cnt{0};
    while ((mask >> cnt) != 0)
    {
      if ((mask >> cnt) & 1)
      {
        merge(cnt);
      }
      ++cnt;
    }
  }

  vector<Point> path() const
  {
    vector<Point> ans;
    for (auto const &e : V)
    {
      auto tmp{e.path()};
      copy(tmp.begin(), tmp.end(), back_inserter(ans));
    }
    return ans;
  }

  vector<Cycle> const &seq() const
  {
    return V;
  }

  void operator+=(Chain const &other)
  {
    copy(other.seq().begin(), other.seq().end(), back_inserter(V));
  }

private:
  void merge(int n)
  {
    if (V.empty())
    {
      V.push_back(Cycle{n, true});
    }
    else
    {
      auto inverse{inv()};
      *this += Chain{Cycle{n, true}};
      *this += inverse;
      *this += Chain{Cycle{n, false}};
    }
  }

  Chain inv() const
  {
    vector<Cycle> W;
    for (auto it = V.rbegin(); it != V.rend(); ++it)
    {
      W.push_back(it->inv());
    }
    return Chain(W);
  }
};

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

class Solve
{
  int N;
  vector<bool> V;
  Chain C;
  bool possible;

public:
  Solve(int N, string A) : N{N}, V(1 << N), possible{true}
  {
    for (auto i = 0; i < 1 << N; ++i)
    {
      V[i] = (A[i] == '1');
    }
  }

  void answer()
  {
    if (check())
    {
      construct();
    }
    else
    {
      possible = false;
    }
    flush();
  }

private:
  bool check() const
  {
    for (auto i = 0; i < 1 << N; ++i)
    {
      for (auto j = 0; j < 1 << N; ++j)
      {
        if ((i & j) == j)
        {
          if (!V[j] && V[i])
          {
            return false;
          }
        }
      }
    }
    return true;
  }

  void construct()
  {
    for (auto i = 0; i < 1 << N; ++i)
    {
      if (V[i])
      {
        continue;
      }
#if DEBUG == 1
      cerr << "i = " << i << endl;
#endif
      bool create{true};
      for (auto j = 0; j < 1 << N; ++j)
      {
        if ((i & j) == j && !V[j])
        {
          create = false;
          break;
        }
      }
      if (create)
      {
        C += Chain{i};
      }
    }
  }

  void flush() const
  {
    if (possible)
    {
      cout << "Possible" << endl;
    }
    else
    {
      cout << "Impossible" << endl;
      return;
    }
    auto tmp{C.path()};
    cout << tmp.size() << endl;
    for (auto const &e : tmp)
    {
      cout << e << endl;
    }
  }
};

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

int main()
{
  int N;
  cin >> N;
  string A;
  cin >> A;
  Solve solve(N, A);
  solve.answer();
}
<commit_msg>tried E.cpp to 'E'<commit_after>#define DEBUG 1
/**
 * File    : E.cpp
 * Author  : Kazune Takahashi
 * Created : 4/23/2020, 7:08:47 PM
 * Powered by Visual Studio Code
 */
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cctype>
#include <chrono>
#include <cmath>
#include <complex>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <random>
#include <set>
#include <stack>
#include <string>
#include <tuple>
#include <unordered_map>
#include <unordered_set>
#include <vector>
// ----- boost -----
#include <boost/rational.hpp>
#include <boost/multiprecision/cpp_int.hpp>
// ----- using directives and manipulations -----
using namespace std;
using boost::rational;
using boost::multiprecision::cpp_int;
using ll = long long;
template <typename T>
using max_heap = priority_queue<T>;
template <typename T>
using min_heap = priority_queue<T, vector<T>, greater<T>>;
// ----- constexpr for Mint and Combination -----
constexpr ll MOD{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 + MOD) % 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++() { return *this += 1; }
  Mint &operator++(int)
  {
    Mint tmp{*this};
    ++*this;
    return tmp;
  }
  Mint &operator--() { return *this -= 1; }
  Mint &operator--(int)
  {
    Mint tmp{*this};
    --*this;
    return tmp;
  }
  Mint &operator*=(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>;
template <typename T>
T gcd(T x, T y) { return y ? gcd(y, x % y) : x; }
template <typename T>
T lcm(T x, T y) { return x / gcd(x, y) * y; }
// ----- for C++17 -----
template <typename T>
int popcount(T x) // C++20
{
  int ans{0};
  while (x != 0)
  {
    ans += x & 1;
    x >>= 1;
  }
  return ans;
}
// ----- frequently used constexpr -----
// constexpr double epsilon{1e-10};
// constexpr ll infty{1000000000000000LL}; // or
// constexpr int infty{1'000'000'010};
// constexpr int dx[4] = {1, 0, -1, 0};
// constexpr int dy[4] = {0, 1, 0, -1};
// ----- Yes() and No() -----
void Yes()
{
  cout << "Yes" << endl;
  exit(0);
}
void No()
{
  cout << "No" << endl;
  exit(0);
}

// ----- Point -----

using Point = tuple<int, int>;

ostream &operator<<(ostream &os, Point const &pt)
{
  return os << get<0>(pt) << " " << get<1>(pt);
}

// ----- Cycle -----

class Cycle
{
  int num;
  bool pos;

public:
  Cycle(int num, bool pos) : num{num}, pos{pos} {}

  vector<Point> path() const
  {
    vector<Point> ans;
    for (auto i = 0; i <= num; ++i)
    {
      ans.push_back(Point(i, 0));
    }
    if (pos)
    {
      ans.push_back(Point(num + 1, 0));
      ans.push_back(Point(num + 1, 1));
      ans.push_back(Point(num, 1));
    }
    else
    {
      ans.push_back(Point(num, 1));
      ans.push_back(Point(num + 1, 1));
      ans.push_back(Point(num + 1, 0));
    }
    for (auto i = num; i >= 1; --i)
    {
      ans.push_back(Point(i, 0));
    }
    return ans;
  }

  Cycle inv() const
  {
    return Cycle(num, !pos);
  }
};

class Chain
{
  vector<Cycle> V;

public:
  Chain() {}
  Chain(Cycle c) : V{c} {}
  Chain(vector<Cycle> V) : V(V) {}

  Chain(int mask)
  {
#if DEBUG == 1
    cerr << "mask = " << mask << endl;
#endif
    int cnt{0};
    while ((mask >> cnt) != 0)
    {
      if ((mask >> cnt) & 1)
      {
        merge(cnt);
      }
      ++cnt;
    }
  }

  vector<Point> path() const
  {
    vector<Point> ans;
    for (auto const &e : V)
    {
      auto tmp{e.path()};
      copy(tmp.begin(), tmp.end(), back_inserter(ans));
    }
    return ans;
  }

  vector<Cycle> const &seq() const
  {
    return V;
  }

  void operator+=(Chain const &other)
  {
    copy(other.seq().begin(), other.seq().end(), back_inserter(V));
  }

private:
  void merge(int n)
  {
    if (V.empty())
    {
      V.push_back(Cycle{n, true});
    }
    else
    {
      auto inverse{inv()};
      *this += Chain{Cycle{n, true}};
      *this += inverse;
      *this += Chain{Cycle{n, false}};
    }
  }

  Chain inv() const
  {
    vector<Cycle> W;
    for (auto it = V.rbegin(); it != V.rend(); ++it)
    {
      W.push_back(it->inv());
    }
    return Chain(W);
  }
};

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

class Solve
{
  int N;
  vector<bool> V;
  Chain C;
  bool possible;

public:
  Solve(int N, string A) : N{N}, V(1 << N), possible{true}
  {
    for (auto i = 0; i < 1 << N; ++i)
    {
      V[i] = (A[i] == '1');
    }
  }

  void answer()
  {
    if (check())
    {
      construct();
    }
    else
    {
      possible = false;
    }
    flush();
  }

private:
  bool check() const
  {
    if (!V[0])
    {
      return false;
    }
    for (auto i = 0; i < 1 << N; ++i)
    {
      for (auto j = 0; j < 1 << N; ++j)
      {
        if ((i & j) == j)
        {
          if (!V[j] && V[i])
          {
            return false;
          }
        }
      }
    }
    return true;
  }

  void construct()
  {
    for (auto i = 0; i < 1 << N; ++i)
    {
      if (V[i])
      {
        continue;
      }
#if DEBUG == 1
      cerr << "i = " << i << endl;
#endif
      bool create{true};
      for (auto j = 0; j < 1 << N; ++j)
      {
        if ((i & j) == j && !V[j])
        {
          create = false;
          break;
        }
      }
      if (create)
      {
        C += Chain{i};
      }
    }
  }

  void flush() const
  {
    if (possible)
    {
      cout << "Possible" << endl;
    }
    else
    {
      cout << "Impossible" << endl;
      return;
    }
    auto tmp{C.path()};
    cout << tmp.size() << endl;
    tmp.push_back(Point(0, 0));
    for (auto const &e : tmp)
    {
      cout << e << endl;
    }
  }
};

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

int main()
{
  int N;
  cin >> N;
  string A;
  cin >> A;
  Solve solve(N, A);
  solve.answer();
}
<|endoftext|>


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

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

class Solve
{
  ll N, K;
  map<ll, mint> M;

public:
  Solve(ll N, ll K) : N{N}, K{K}
  {
#if DEBUG == 1
    cerr << "N = " << N << ", K = " << K << endl;
#endif
  }

  void flush()
  {
    mint ans{0};
    auto V{table()};
    for (auto i{1LL}; i <= K; ++i)
    {
      ans += V[i] * i;
#if DEBUG == 1
      if (K == 2)
      {
        cerr << "V[" << i << "] = " << V[i] << endl;
      }
#endif
    }
    cout << ans << endl;
  }

private:
  vector<mint> table()
  {
    vector<mint> V(K + 1, 0);
    for (auto X{K}; X >= 1; --X)
    {
      V[X] = count(K);
      for (auto i{2LL};; ++i)
      {
        if (auto t{X * i}; t <= K)
        {
          V[X] -= V[t];
        }
        else
        {
          break;
        }
      }
    }
    return V;
  }

  mint count(ll X)
  {
    return mint{K / X}.power(N);
  }
};

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

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

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

class Solve
{
  ll N, K;
  map<ll, mint> M;

public:
  Solve(ll N, ll K) : N{N}, K{K}
  {
#if DEBUG == 1
    cerr << "N = " << N << ", K = " << K << endl;
#endif
  }

  void flush()
  {
    mint ans{0};
    auto V{table()};
    for (auto i{1LL}; i <= K; ++i)
    {
      ans += V[i] * i;
#if DEBUG == 1
      if (K == 2)
      {
        cerr << "V[" << i << "] = " << V[i] << endl;
      }
#endif
    }
    cout << ans << endl;
  }

private:
  vector<mint> table()
  {
    vector<mint> V(K + 1, 0);
    for (auto X{K}; X >= 1; --X)
    {
      V[X] = count(X);
      for (auto i{2LL};; ++i)
      {
        if (auto t{X * i}; t <= K)
        {
          V[X] -= V[t];
        }
        else
        {
          break;
        }
      }
    }
    return V;
  }

  mint count(ll X)
  {
    return mint{K / X}.power(N);
  }
};

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

int main()
{
  ll N, K;
  cin >> N >> K;
  Solve solve(N, K);
  solve.flush();
}
<|endoftext|>


<commit_before>//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  Action class - implementation and auxiliary functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CompilerDriver/Action.h"
#include "llvm/CompilerDriver/BuiltinOptions.h"
#include "llvm/CompilerDriver/Error.h"
#include "llvm/CompilerDriver/Main.h"

#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/System/Program.h"
#include "llvm/System/TimeValue.h"

#include <stdexcept>
#include <string>

using namespace llvm;
using namespace llvmc;

namespace llvmc {

extern const char* ProgramName;

}

namespace {

  void PrintString (const std::string& str) {
    errs() << str << ' ';
  }

  void PrintCommand (const std::string& Cmd, const StrVector& Args) {
    errs() << Cmd << ' ';
    std::for_each(Args.begin(), Args.end(), &PrintString);
    errs() << '\n';
  }

  bool IsSegmentationFault (int returnCode) {
#ifdef LLVM_ON_WIN32
    return (returnCode >= 0xc0000000UL)
#else
    return (returnCode < 0);
#endif
  }

  int ExecuteProgram (const std::string& name,
                      const StrVector& args) {
    sys::Path prog(name);

    if (!prog.isAbsolute())
      prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main);

    if (prog.isEmpty()) {
      prog = sys::Program::FindProgramByName(name);
      if (prog.isEmpty()) {
        PrintError("Can't find program '" + name + "'");
        return -1;
      }
    }
    if (!prog.canExecute()) {
      PrintError("Program '" + name + "' is not executable.");
      return -1;
    }

    // Build the command line vector and the redirects array.
    const sys::Path* redirects[3] = {0,0,0};
    sys::Path stdout_redirect;

    std::vector<const char*> argv;
    argv.reserve((args.size()+2));
    argv.push_back(name.c_str());

    for (StrVector::const_iterator B = args.begin(), E = args.end();
         B!=E; ++B) {
      if (*B == ">") {
        ++B;
        stdout_redirect.set(*B);
        redirects[1] = &stdout_redirect;
      }
      else {
        argv.push_back((*B).c_str());
      }
    }
    argv.push_back(0);  // null terminate list.

    // Invoke the program.
    int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);

    if (IsSegmentationFault(ret)) {
      errs() << "Segmentation fault: ";
      PrintCommand(name, args);
    }

    return ret;
  }
}

namespace llvmc {
  void AppendToGlobalTimeLog (const std::string& cmd, double time);
}

int llvmc::Action::Execute () const {
  if (DryRun || VerboseMode)
    PrintCommand(Command_, Args_);

  if (!DryRun) {
    if (Time) {
      sys::TimeValue now = sys::TimeValue::now();
      int ret = ExecuteProgram(Command_, Args_);
      sys::TimeValue now2 = sys::TimeValue::now();
      now2 -= now;
      double elapsed = now2.seconds()  + now2.microseconds()  / 1000000.0;
      AppendToGlobalTimeLog(Command_, elapsed);

      return ret;
    }
    else {
      return ExecuteProgram(Command_, Args_);
    }
  }

  return 0;
}
<commit_msg>llvmc: Fix tool finding logic.<commit_after>//===--- Action.cpp - The LLVM Compiler Driver ------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open
// Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  Action class - implementation and auxiliary functions.
//
//===----------------------------------------------------------------------===//

#include "llvm/CompilerDriver/Action.h"
#include "llvm/CompilerDriver/BuiltinOptions.h"
#include "llvm/CompilerDriver/Error.h"
#include "llvm/CompilerDriver/Main.h"

#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SystemUtils.h"
#include "llvm/System/Program.h"
#include "llvm/System/TimeValue.h"

#include <stdexcept>
#include <string>

using namespace llvm;
using namespace llvmc;

namespace llvmc {

extern const char* ProgramName;

}

namespace {

  void PrintString (const std::string& str) {
    errs() << str << ' ';
  }

  void PrintCommand (const std::string& Cmd, const StrVector& Args) {
    errs() << Cmd << ' ';
    std::for_each(Args.begin(), Args.end(), &PrintString);
    errs() << '\n';
  }

  bool IsSegmentationFault (int returnCode) {
#ifdef LLVM_ON_WIN32
    return (returnCode >= 0xc0000000UL)
#else
    return (returnCode < 0);
#endif
  }

  int ExecuteProgram (const std::string& name, const StrVector& args) {
    sys::Path prog(name);

    if (!prog.isAbsolute()) {
      prog = FindExecutable(name, ProgramName, (void *)(intptr_t)&Main);

      if (!prog.canExecute()) {
        prog = sys::Program::FindProgramByName(name);
        if (prog.isEmpty()) {
          PrintError("Can't find program '" + name + "'");
          return -1;
        }
      }
    }
    if (!prog.canExecute()) {
      PrintError("Program '" + name + "' is not executable.");
      return -1;
    }

    // Build the command line vector and the redirects array.
    const sys::Path* redirects[3] = {0,0,0};
    sys::Path stdout_redirect;

    std::vector<const char*> argv;
    argv.reserve((args.size()+2));
    argv.push_back(name.c_str());

    for (StrVector::const_iterator B = args.begin(), E = args.end();
         B!=E; ++B) {
      if (*B == ">") {
        ++B;
        stdout_redirect.set(*B);
        redirects[1] = &stdout_redirect;
      }
      else {
        argv.push_back((*B).c_str());
      }
    }
    argv.push_back(0);  // null terminate list.

    // Invoke the program.
    int ret = sys::Program::ExecuteAndWait(prog, &argv[0], 0, &redirects[0]);

    if (IsSegmentationFault(ret)) {
      errs() << "Segmentation fault: ";
      PrintCommand(name, args);
    }

    return ret;
  }
}

namespace llvmc {
  void AppendToGlobalTimeLog (const std::string& cmd, double time);
}

int llvmc::Action::Execute () const {
  if (DryRun || VerboseMode)
    PrintCommand(Command_, Args_);

  if (!DryRun) {
    if (Time) {
      sys::TimeValue now = sys::TimeValue::now();
      int ret = ExecuteProgram(Command_, Args_);
      sys::TimeValue now2 = sys::TimeValue::now();
      now2 -= now;
      double elapsed = now2.seconds()  + now2.microseconds()  / 1000000.0;
      AppendToGlobalTimeLog(Command_, elapsed);

      return ret;
    }
    else {
      return ExecuteProgram(Command_, Args_);
    }
  }

  return 0;
}
<|endoftext|>