#include <bits/stdc++.h>
#include <math.h>
#include <unordered_map>
#include <unordered_set>
#include <tuple>

#define io ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define PB push_back
#define MP make_pair
#define REP(i,a,b) for (ll i = a; i < b; i++)
#define enl "\n"
#define INF std::numeric_limits<ll>::max()
#define F first
#define S second

using namespace std;

typedef long long int ll;
typedef unsigned long long int ull;
typedef long double ldb;
typedef vector<long long> vll;
typedef pair<long long,long long> pll;

ll greatestSubarraySum(ll array[], ll n);
ll binarySearch(vll arr, ll l, ll r, ll x);
ll modpower(ll x, ll y, ll p);
ll power(ll x, ll y);
ll gcd(ll a, ll b);
ll lcm(ll a, ll b);
ll search(ll arr[], ll n, ll k);
string findSum(string str1, string str2);
ll extendedGcd(ll a, ll b, ll & x, ll & y);
bool find_any_solution(ll a, ll b, ll c, ll &x0, ll &y0, ll &g);
ll countSetBits(ll n);
void primeFactors(ll n, map<ll,ll>& arr2, ll k, ll& flaggy);
void matrixMultiply(ll a[3][3], ll b[3][3]);
void matrixPower(ll F[7][7], ll n);
ll sumSquareRootDecomposition(ll arr[], vll helper, ll n, ll l, ll r);
vll squareRootDecompositionSumArray(ll arr[], ll n);
ll minSquareRootDecomposition(ll arr[], vll helper, ll n, ll l, ll r);
ll maxSquareRootDecomposition(ll arr[], vll helper, ll n, ll l, ll r);
vll squareRootDecompositionMinArray(ll arr[], ll n);
vll squareRootDecompositionMaxArray(ll arr[], ll n);
void updateSquareRootDecompositionMinArray(ll arr[], vll &helper, ll n, ll i, ll x);
void updateSquareRootDecompositionMaxArray(ll arr[], vll &helper, ll n, ll i, ll x);
void updateSquareRootDecompositionSumArray(ll arr[], vll &helper, ll n, ll i, ll x);
void dfs(ll i, set<ll> arr[], ll visited[]);
void uni(ll x, ll y, ll par[], ll size[]);
ll find(ll x, ll par[], ll size[]);
ll modulo( ll value, ll m);
class FenwickTree;
void pairsort(ll a[], ll b[], ll n);
ll max(ll a, ll b);
ll min(ll a, ll b);
ll modInverse(ll a, ll m);
ll modsum(ll a, ll b, ll m);
ll modmul(ll a, ll b, ll m);
string reverseOfString(string s);
ll nCrMod(ll n, ll r, ll mod);
vll kmpArray(string s);

#define MAXI 998244353

ll fact[1000000];

ll floorSqrt(ll x)
{
    // Base cases
    if (x == 0 || x == 1)
       return x;

    // Do Binary Search for floor(sqrt(x))
    ll start = 1, end = x, ans;
    while (start <= end)
    {
        ll mid = (start + end) / 2;

        // If x is a perfect square
        if (mid*mid == x)
            return mid;

        // Since we need floor, we update answer when mid*mid is
        // smaller than x, and move closer to sqrt(x)
        if (mid*mid < x)
        {
            start = mid + 1;
            ans = mid;
        }
        else // If mid*mid is greater than x
            end = mid-1;
    }
    return ans;
}

int main(){

    io

    ll q=1;
    // cin>>q;
    REP(currentIndex,0,q){

        ll n,k;
        cin>>n>>k;

        ll current[k+1];
        REP(i,0,k+1)current[i]=0;

        ll ans=0;

        REP(i,1,k+1){

            ll temp=0;

            if(i==1){

                current[i]=1;

            } else {

                for(ll j=1; j<=floorSqrt(i); j++){

                    if(i%j==0){

                        temp+=current[j];
                        if(j!=i/j)temp+=current[i/j];
                    }

                }

                current[i]=i-temp;

            }

            ans=modsum(ans, modmul(i-temp, modpower(k/i, n, 1000000007), 1000000007), 1000000007);

        }

        cout<<ans<<endl;

    }

}

vll kmpArray(string s){

    vll arr(s.length(), 0);

    REP(i,1,s.length()){

        ll len=arr[i-1];
        while(len>0 && s[len]!=s[i])len=arr[len-1];
        if(s[len]==s[i])len++;
        arr[i]=len;

    }

    return arr;

}

ll nCrMod(ll n, ll r, ll mod){

    return (fact[n]* modInverse(fact[r], mod) % mod * modInverse(fact[n-r], mod) % mod) % mod;

}

void SieveOfEratosthenes(ll n, bool isPrime[])
{

    isPrime[0] = isPrime[1] = false;
    for (ll i = 2; i <= n; i++)
        isPrime[i] = true;

    for (ll p = 2; p * p <= n; p++) {

        if (isPrime[p] == true) {

            for (ll i = p * 2; i <= n; i += p)
                isPrime[i] = false;
        }
    }
}

string reverseOfString(string s){

    string t;
    REP(i,0,s.length()){

        t+=s[s.length()-i-1];

    }

    return t;

}

class FenwickTree{

private:
    ll n;

    ll h(ll i){return (i|(i+1));}
    ll g(ll i){return (i&(i+1));}

public:

    ll *sumtree;
    ll *mainArray;

    FenwickTree(ll n){

        this->n=n;
        mainArray = (ll*)malloc(n*sizeof(ll));
        sumtree = (ll*)calloc(n, sizeof(ll));

    }

    void addElementAtIndex(ll i, ll x){
        mainArray[i]=x;
        update(i,x);
    }

    void update(ll i, ll delta){

        for(ll j=i; j<n; j=h(j)){
            sumtree[j]+=delta;

        }

    }

    ll sum(ll i, ll j){

        ll sum1=0, sum2=0;
        ll i1=i,j1=j;
        while(j>=0){
            sum1+=sumtree[j];
            j=g(j)-1;
        }
        while(i>=0){
            sum2+=sumtree[i];
            i=g(i)-1;
        }
        return sum1-sum2+mainArray[i1];

    }

};

ll modsum(ll a, ll b, ll m){

    return ((a%m)+(b%m))%m;

}

ll modmul(ll a, ll b, ll m){

    return ((a%m)*(b%m))%m;

}

ll modInverse(ll a, ll m)
{

    return modpower(a, m-2, m);

}

ll max(ll a, ll b){

    if(a>b)return a;
    else return b;
}

ll min(ll a, ll b){

    if(a<b)return a;
    return b;

}

void pairsort(ll a[], ll b[], ll n)
{
    pair<ll, ll> pairt[n];

    for (ll i = 0; i < n; i++)
    {
        pairt[i].first = a[i];
        pairt[i].second = b[i];
    }

    sort(pairt, pairt + n);

    for (ll i = 0; i < n; i++)
    {
        a[i] = pairt[i].first;
        b[i] = pairt[i].second;
    }
}

ll extendedGcd(ll a, ll b, ll & x, ll & y) {
    if (a == 0) {
        x = 0;
        y = 1;
        return b;
    }
    ll x1, y1;
    ll d = extendedGcd(b % a, a, x1, y1);
    x = y1 - (b / a) * x1;
    y = x1;
    return d;
}

bool find_any_solution(ll a, ll b, ll c, ll &x0, ll &y0, ll &g) {
    g = extendedGcd(abs(a), abs(b), x0, y0);
    if (c % g) {
        return false;
    }

    x0 *= c / g;
    y0 *= c / g;
    if (a < 0) x0 = -x0;
    if (b < 0) y0 = -y0;
    return true;
}

string findSum(string str1, string str2)
{

    if (str1.length() > str2.length()) {
        string s = str1;
        str1=str2;
        str2=s;
    }

    string str = "";

    int n1 = str1.length(), n2 = str2.length();

    reverse(str1.begin(), str1.end());
    reverse(str2.begin(), str2.end());

    int carry = 0;
    for (int i=0; i<n1; i++)
    {

        int sum = ((str1[i]-'0')+(str2[i]-'0')+carry);
        str.push_back(sum%10 + '0');

        carry = sum/10;
    }

    // Add remaining digits of larger number
    for (int i=n1; i<n2; i++)
    {
        int sum = ((str2[i]-'0')+carry);
        str.push_back(sum%10 + '0');
        carry = sum/10;
    }

    // Add remaining carry
    if (carry)
        str.push_back(carry+'0');

    // reverse resultant string
    reverse(str.begin(), str.end());

    return str;
}

ll binarySearch(vll arr, ll l, ll r, ll x)
{
    if (r >= l) {
        ll mid = l + (r - l) / 2;

        // If the element is present at the middle
        // itself
        if (arr[mid] == x)
            return mid;

        // If element is smaller than mid, then
        // it can only be present in left subarray
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);

        // Else the element can only be present
        // in right subarray
        return binarySearch(arr, mid + 1, r, x);
    }

    // We reach here when element is not
    // present in array
    return -1;
}

ll greatestSubarraySum(ll array[], ll n){

    ll best = 0, sum = 0;
    for (ll k = 0; k < n; k++) {
        sum = max(array[k],sum+array[k]);
        best = max(best,sum);
    }

    return best;
}

ll modpower(ll x, ll y, ll p)
{
    ll res = 1;      // Initialize result

    x = x % p;  // Update x if it is more than or
                // equal to p

    while (y > 0)
    {
        // If y is odd, multiply x with result
        if (y & 1)
            res = (res*x) % p;

        // y must be even now
        y = y>>1; // y = y/2
        x = (x*x) % p;
    }
    return res;
}

ll gcd(ll a, ll b)
{
    if (a == 0)
        return b;

    return gcd(b%a, a);
}

ll lcm(ll a, ll b)
{
    return (a*b)/gcd(a, b);
}

ll power(ll x, ll y)
{
    ll temp;
    if( y == 0)
        return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
        return temp*temp;
    else
        return x*temp*temp;
}

ll modulo( ll value, ll m) {
    ll mod = value % m;
    if (value < 0) {
        mod += m;
    }
    return mod;
}

ll find(ll x, ll par[], ll size[]){

    if(x==par[x])return x;
    else return par[x]=find(par[x],par, size);

}

void uni(ll x, ll y, ll par[], ll size[]){

    x=find(x,par,size);
    y=find(y,par,size);

    if(size[x]>size[y])swap(x,y);

    par[x]=y;
    size[y]+=size[x];

}

void dfs(ll i, set<ll> arr[], ll visited[]){

    if(visited[i])return;

    cout<<(char)('a'+i);

    visited[i]=1;

    for(auto u:arr[i])dfs(u, arr, visited);

}

ll countSetBits(ll n)
{
    ll count = 0;
    while (n) {
        count += n & 1;
        n >>= 1;
    }
    return count;
}

ll flag2;

void primeFactors(ll n, map<ll,ll>& arr2, ll k, ll& flaggy)
{
    ll count=0;

    ll flag=0;

    while (n % 2 == 0)
    {
        n = n/2;
        count++;
    }

    if(count%k != 0){

        flag=1;

        arr2[2]=count%k;

    }
    count=0;

    for (int i = 3; i <= sqrt(n); i = i + 2)
    {
        while (n % i == 0)
        {
            n = n/i;
            count++;
        }

        if(count%k!=0){

            flag=1;
            arr2[i]=count%k;

        }

        count=0;
    }

    if (n > 2)
        {
            if(1%k!=0){

                flag=1;
                arr2[n]=1%k;

            }
        }

        if(flag==0){flag2++;flaggy=1;}

}

void matrixMultiply(ll* a[], ll *b[], ll n)
{

    ll mul[n][n];
    for (ll i = 0; i < n; i++)
    {
        for (ll j = 0; j < n; j++)
        {
            mul[i][j] = 0;
            for (ll k = 0; k < n; k++)
                mul[i][j] += a[i][k]*b[k][j];
        }
    }

    for (int i=0; i<n; i++)
        for (int j=0; j<n; j++)
            a[i][j] = mul[i][j];
}

void matrixPower(ll **F, ll n, ll k)
{

    if(n==1)return;

    ll **M = (ll **)malloc(k*sizeof(ll *));

    REP(i,0,k){
        M[i]=(ll *)malloc(k*sizeof(ll));
        REP(j,0,k){
            M[i][j]=F[i][j];
        }
    }

    matrixPower(F, n/2, k);

    matrixMultiply(F, F, k);

    if (n%2 != 0)
        matrixMultiply(F, M,k);

}

vll squareRootDecompositionMinArray(ll arr[], ll n){

    ll k=(ll)ceil(sqrt(n));
    vll helper(k,INF);

    REP(i,0,n)helper[i/k]=min(helper[i/k],arr[i]);

    return helper;

}
vll squareRootDecompositionMaxArray(ll arr[], ll n){

    ll k=(ll)ceil(sqrt(n));
    vll helper(k,-INF);

    REP(i,0,n)helper[i/k]=max(helper[i/k],arr[i]);

    return helper;

}

ll minSquareRootDecomposition(ll arr[], vll helper, ll n, ll l, ll r){

    ll k=(ll)ceil(sqrt(n));

    ll a=l/k;
    ll b=r/k;

    ll min1=INF;

    if(a==b){

        REP(i,l,r+1)min1=min(min1,arr[i]);

        return min1;
    }

    REP(i,l,(a+1)*k)min1=min(min1,arr[i]);
    REP(i,a+1,b)min1=min(min1,helper[i]);
    REP(i,b*k,r+1)min1=min(min1,arr[i]);

    return min1;

}
ll maxSquareRootDecomposition(ll arr[], vll helper, ll n, ll l, ll r){

    ll k=(ll)ceil(sqrt(n));

    ll a=l/k;
    ll b=r/k;

    ll min1=-INF;

    if(a==b){

        REP(i,l,r+1)min1=max(min1,arr[i]);

        return min1;
    }

    REP(i,l,(a+1)*k)min1=max(min1,arr[i]);
    REP(i,a+1,b)min1=max(min1,helper[i]);
    REP(i,b*k,r+1)min1=max(min1,arr[i]);

    return min1;

}

vll squareRootDecompositionSumArray(ll arr[], ll n){

    ll k=(ll)ceil(sqrt(n));

    //preprocessed array

    vll helper(k,0);

    //preprocessing

    REP(i,0,n)helper[i/k]+=arr[i];

    return helper;

}

void updateSquareRootDecompositionSumArray(ll arr[], vll &helper, ll n, ll i, ll x){

    ll k=(ll)ceil(sqrt(n));
    ll delta=x-arr[i];
    arr[i]=x;
    helper[i/k]+=delta;

}

void updateSquareRootDecompositionMinArray(ll arr[], vll &helper, ll n, ll i, ll x){

    ll k=(ll)ceil(sqrt(n));
    if(helper[i/k]==arr[i]){

        if(x<arr[i])helper[i/k]=arr[i];
        else{

            ll min1=INF;
            REP(j,i/k*k,(i/k+1)*k)min1=min(min1,arr[j]);
            helper[i/k]=min1;

        }

    } else{

        helper[i/k]=min(helper[i/k],x);
    }

    arr[i]=x;

}
void updateSquareRootDecompositionMaxArray(ll arr[], vll &helper, ll n, ll i, ll x){

    ll k=(ll)ceil(sqrt(n));
    if(helper[i/k]==arr[i]){

        if(x<arr[i])helper[i/k]=arr[i];
        else{

            ll min1=-INF;
            REP(j,i/k*k,(i/k+1)*k)min1=max(min1,arr[j]);
            helper[i/k]=min1;

        }

    } else{

        helper[i/k]=max(helper[i/k],x);
    }

    arr[i]=x;

}

ll sumSquareRootDecomposition(ll arr[], vll helper, ll n, ll l, ll r){

    ll k=(ll)ceil(sqrt(n));

    ll a=l/k;
    ll b=r/k;

    ll sum=0;

    if(a==b){

        REP(i,l,r+1)sum+=arr[i];

        return sum;

    }

    REP(i,l,(a+1)*k){sum+=arr[i];}
    REP(i,b*k,r+1)sum+=arr[i];
    REP(i,a+1,b)sum+=helper[i];

    return sum;

}


#include <bits/stdc++.h>
#include <variant>
#include <boost/range/algorithm.hpp>
#include <boost/range/numeric.hpp>
#include <boost/range/irange.hpp>
#include <boost/range/adaptor/indexed.hpp>
#define FOR(i,k,n)  for(int i = (k);i < (n);++i)
#define REP(i,n)    FOR(i,0,n)
#define ALL(x) begin(x),end(x)

using namespace std;
using namespace boost::adaptors;
using namespace std::string_literals;
using ll = int64_t;
using vecint = vector<int>;
using vecll = vector<ll>;
using boost::irange;
constexpr ll MOD = 1000000007;

ll pmod(ll base, ll index) {
  if (index == 0) return 1;
  if (index%2 == 1) return pmod(base, index-1) * base % MOD;
  ll h = pmod(base, index/2);
  return h * h % MOD;
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  ll n,k;
  cin>>n>>k;
  vecll v(k+1);
  FOR(i,1,k+1) {
    v[i] = pmod(k/i, n);
  }
  for (int i = k; i > 0; --i) {
    for (int j = 2*i; j <= k; j += i) {
      v[i] += MOD - v[j];
      v[i] %= MOD;
    }
  }
  ll ans = 0;
  FOR(i,1,k+1) {
    ans += i * v[i] % MOD;
    ans %= MOD;
  }
  cout<<ans<<endl;
  return 0;
}

Global OOD problem IDs are disjoint from train, validation, and in-distribution test problem IDs.

Score : 500 points

Problem Statement

Consider sequences \{A_1,...,A_N\} of length N consisting of integers between 1 and K (inclusive).

There are K^N such sequences. Find the sum of \gcd(A_1, ..., A_N) over all of them.

Since this sum can be enormous, print the value modulo (10^9+7).

Here \gcd(A_1, ..., A_N) denotes the greatest common divisor of A_1, ..., A_N.

Constraints

2 \leq N \leq 10^5

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the sum of \gcd(A_1, ..., A_N) over all K^N sequences, modulo (10^9+7).

Sample Input 1

3 2

Sample Output 1

9

\gcd(1,1,1)+\gcd(1,1,2)+\gcd(1,2,1)+\gcd(1,2,2)
+\gcd(2,1,1)+\gcd(2,1,2)+\gcd(2,2,1)+\gcd(2,2,2)
=1+1+1+1+1+1+1+2=9

Thus, the answer is 9.

Sample Input 2

3 200

Sample Output 2

10813692

Sample Input 3

100000 100000

Sample Output 3

742202979

Be sure to print the sum modulo (10^9+7).

Submitted source-code file size, in bytes.

Execution CPU time reported by official Project CodeNet metadata, in milliseconds.

Peak memory usage reported by official Project CodeNet metadata, in kilobytes.


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
const int mod=1000000007;
const double PI = 3.14159265359;
#define mxe(v) *max_element(v.begin(),v.end())
#define mne(v) *min_element(v.begin(),v.end())
#define INF 1000000000000
#define pb push_back
#define pf push_front
#define ppb pop_back
#define ppf pop_front
#define mp make_pair
#define lb lower_bound
#define ub upper_bound
#define FOR(i,n) for(int i=0;i<(n);i++)
#define FORA(i,a,b) for(int i=(a);i<=(b);i++)
#define FORD(i,a,b) for(int i=(a);i>=(b);i--)
#define FAST ios_base::sync_with_stdio(false);cin.tie(NULL);
#define count_1(n)  __builtin_popcountll(n)
#define parity(n)   __builtin_parityll(n)   //Even parity 0 as output
void show    (int a[], int arraysize) { for (int i = 0; i < arraysize; ++i)  {cout << a[i] << " ";}	cout<<endl;}
int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b);}
void sieve(int n)
{
    bool prime[n+1];
    memset(prime, true, sizeof(prime));

    for (int p=2; p*p<=n; p++)
    {
        if (prime[p] == true)
        {
            for (int i=p*p; i<=n; i += p)
                prime[i] = false;
        }
    }
    for (int p=2; p<=n; p++)
       if (prime[p])
          cout << p << " ";
}
int main()
{FAST
int n,k;
cin>>n>>k;
if(k>=n)
{
	cout<<min(n,abs(n-k));
}
else
{
	cout<<n%k<<endl;
}
return  0;
}

Score : 300 points

Problem Statement

Given any integer x, Aoki can do the operation below.

Operation: Replace x with the absolute difference of x and K.

You are given the initial value of an integer N. Find the minimum possible value taken by N after Aoki does the operation zero or more times.

Constraints

0 ≤ N ≤ 10^{18}

1 ≤ K ≤ 10^{18}

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N K

Output

Print the minimum possible value taken by N after Aoki does the operation zero or more times.

Sample Input 1

7 4

Sample Output 1

1

Initially, N=7.

After one operation, N becomes |7-4| = 3.

After two operations, N becomes |3-4| = 1, which is the minimum value taken by N.

Sample Input 2

2 6

Sample Output 2

2

N=2 after zero operations is the minimum.

Sample Input 3

1000000000000000000 1

Sample Output 3

0


                   /**Bismillahir Rahmanir Rahim.**/
/*
         Md.Fagun Molla
         18ICTCSE006
         BSMRSTU(SHIICT)
*/
#include <bits/stdc++.h>
using namespace std;

#define  gcd(a,b)         __gcd(a,b)
#define  lcm(a,b)         (a*b)/gcd(a,b)
#define  ll               long long
#define  vi               std::vector<int>
#define  pb               push_back
#define  MAX              100007
#define  End              return 0;
#define  pi               acos(-1)

map<string,int>v;
int main () {
    ios_base::sync_with_stdio(false); cin.tie(0);cout.tie(0);
    ll n,k;
    cin>>n>>k;
    ll x=n%k;
    ll y=abs((n/k+1)*(k)-n);
    //cout<<x<<" "<<y<<endl;
    cout<<min(x,y)<<endl;
    End
}
/* pray for me
Do before die
*/


#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define MIN(a,b) ((a) <= (b) ? (a) : (b))
#define ALL(v) (v).begin(), (v).end()
#define SORT(v) sort( ALL(v) )

using namespace std;
using ll = long long;
using P = pair<int,int>;
using ull  = unsigned long long;

int main()
{

   ll N,K; cin >> N >> K;

   N%=K;
   cout << min(N, K-N)<<endl;
    return 0;
}


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;

int main()
{
  ll N, K;
  cin >> N >> K;
  if (N >= K) {
    N = N % K;
  }
  N = min(N, abs(N-K));
  cout << N << endl;
}


// SeeAlso:

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

#define MAX 100000
#define NIL -1
#define MOD 1000000007

typedef int _loop_int;
#define rep(i,n) for(int i = 0; i < n; i++)
#define FOR(i,a,b) for(_loop_int i=(_loop_int)(a);i<(_loop_int)(b);++i)
#define FORR(i,a,b) for(_loop_int i=(_loop_int)(b)-1;i>=(_loop_int)(a);--i)

#define debug(x) cout<<#x<<": "<<x<<endl
#define debig_vec(v) cout<<#v<<":";rep(i,v.size())cout<<" "<<v[i];cout<<endl
#define ALL(a) (a).begin(),(a).end()

// 最大公約数
inline constexpr ll gcd(ll a,ll b){if(!a||!b)return 0;while(b){ll c=b;b=a%b;a=c;}return a;}
// 最小公倍数
inline constexpr ll lcm(ll a,ll b){if(!a||!b)return 0;return a*b/gcd(a,b);}

#define print2D(h, w, arr) rep(i, h) { rep(j, w) cout << arr[i][j] << " "; cout << endl; }
template<class T> void print(const T& x){cout << setprecision(12) << x << endl;}
template<class T, class... A> void print(const T& first, const A&... rest) { cout << first << " "; print(rest...); }

int main() {
    ll n,k;
    cin>>n>>k;
    ll t = n%k;
    print(min(abs(t-k), t));
    return 0;
}


#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fst first
#define snd second
using namespace std;

typedef long long ll;
typedef double db;
typedef long double ldb;

template<class T> inline void checkmin(T &a,const T &b){if(b<a) a=b;}
template<class T> inline void checkmax(T &a,const T &b){if(b>a) a=b;}

const int inf=1e9+10;
const int maxn=15;
const int mod=2e5;

int dp[maxn][maxn],k,tot[maxn];

int add(int &a,int b){
	a=(a+b)%mod;
}

int main(){
	cin>>k;
	for(int t=0;t<10;t++) dp[1][t]=1;
	for(int i=1;i<=10;i++){
		for(int t=0;t<10;t++){
			if(t-1>=0) add(dp[i+1][t-1],dp[i][t]);
			if(t+1<=9) add(dp[i+1][t+1],dp[i][t]);
			add(dp[i+1][t],dp[i][t]);
		}
		for(int t=1;t<10;t++){
			add(tot[i],dp[i][t]);
		}
		add(tot[i],tot[i-1]);
	}
	int len=1,sum=0;
	for(;;){
		for(int t=1;t<10;t++){
			sum+=dp[len][t];
		}
		if(sum>=k) break;
		len++;
	}
//	cout<<len<<endl;
	int mini=0,maxi=9;
	dp[len][0]=tot[len-1];
	string ans="";
	for(int i=len;i>=1;i--){
		for(int t=mini;t<=maxi;t++){
			if(dp[i][t]>=k){
				mini=max(0,t-1);
				maxi=min(9,t+1);
				ans+=char('0'+t);
				break;
			}
			else{
				k-=dp[i][t];
			//	cout<<i<<" "<<t<<" "<<mini<<" "<<maxi<<" "<<dp[i][t]<<" "<<k<<endl;
			}
		}
	}
	cout<<ans;
	return 0;
}

Score : 400 points

Problem Statement

A positive integer X is said to be a lunlun number if and only if the following condition is satisfied:

In the base ten representation of X (without leading zeros), for every pair of two adjacent digits, the absolute difference of those digits is at most 1.

For example, 1234, 1, and 334 are lunlun numbers, while none of 31415, 119, or 13579 is.

You are given a positive integer K. Find the K-th smallest lunlun number.

Constraints

1 \leq K \leq 10^5

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K

Output

Print the answer.

Sample Input 1

15

Sample Output 1

23

We will list the 15 smallest lunlun numbers in ascending order:

1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
21,
22,
23.

Thus, the answer is 23.

Sample Input 2

1

Sample Output 2

1

Sample Input 3

13

Sample Output 3

21

Sample Input 4

100000

Sample Output 4

3234566667

Note that the answer may not fit into the 32-bit signed integer type.


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
template<typename T1,typename T2> bool chmin(T1 &a,T2 b){if(a<=b)return 0; a=b; return 1;}
template<typename T1,typename T2> bool chmax(T1 &a,T2 b){if(a>=b)return 0; a=b; return 1;}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout << fixed << setprecision(20);

    int n,k,c;
    cin>>n>>k>>c;
    string s;
    cin>>s;
    if(c==0){
        int cnt = 0;
        for(int i=0;i<n;i++){
            if(s[i]='o')cnt++;
        }
        if(cnt == k){
            for(int i=0;i<n;i++){
                if(s[i]=='o'){
                    cout << i +1 << endl;
                }

            }
        }
        return 0;
    }
    vector<int> ans;
    int a[n+1]={};
    int r = 0;
    for(int i=0;i<n;i++){
        if(i) chmax(a[i],a[i-1]);
        if(s[i] == 'o' && i >= r){
            chmax(a[min(n,i+c+1)],a[i]+1);
            r = i+c+1;
        }
    }
    //for(int i=0;i<=n;i++) cout << a[i];
    //cout << endl;
    chmax(a[n],a[n-1]);
    if(a[n] == k){
        int r = n-1;
        for(int p=k-1;p>=0;p--){
            int cnt = 0;
            int v = -1;
            for(int i=r;i>=0;i--){
                if(a[i] != p){
                    r = i;
                    break;
                }
                if(s[i] == 'o'){
                    cnt++;
                    v = i+1;
                }
            }
            //cerr << p << " " << cnt << endl;
            if(cnt == 1){
                ans.push_back(v);
                r = min(r,v-c-2);
            }
        }
    }
    if(ans.size())sort(ans.begin(),ans.end());
    for(auto i:ans){
        cout << i << "\n";
    }

}

Score : 500 points

Problem Statement

Takahashi has decided to work on K days of his choice from the N days starting with tomorrow.

You are given an integer C and a string S. Takahashi will choose his workdays as follows:

After working for a day, he will refrain from working on the subsequent C days.

If the i-th character of S is x, he will not work on Day i, where Day 1 is tomorrow, Day 2 is the day after tomorrow, and so on.

Find all days on which Takahashi is bound to work.

Constraints

1 \leq N \leq 2 \times 10^5

1 \leq K \leq N

0 \leq C \leq N

The length of S is N.

Each character of S is o or x.

Takahashi can choose his workdays so that the conditions in Problem Statement are satisfied.

Input

Input is given from Standard Input in the following format:

N K C
S

Output

Print all days on which Takahashi is bound to work in ascending order, one per line.

Sample Input 1

11 3 2
ooxxxoxxxoo

Sample Output 1

6

Takahashi is going to work on 3 days out of the 11 days. After working for a day, he will refrain from working on the subsequent 2 days.

There are four possible choices for his workdays: Day 1,6,10, Day 1,6,11, Day 2,6,10, and Day 2,6,11.

Thus, he is bound to work on Day 6.

Sample Input 2

5 2 3
ooxoo

Sample Output 2

1
5

There is only one possible choice for his workdays: Day 1,5.

Sample Input 3

5 1 0
ooooo

Sample Output 3

There may be no days on which he is bound to work.

Sample Input 4

16 4 3
ooxxoxoxxxoxoxxo

Sample Output 4

11
16


#include <bits/stdc++.h>
using namespace std;
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
#define flash ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define debug(x) cerr << " - " << #x << ": " << x << endl;
#define debugs(x, y) cerr << " - " << #x << ": " << x << " " << #y << ": " << y << endl;
#define all(x) (x).begin(),(x).end()
#define sz(x) (ll)x.size()
#define ll long long
#define INF 1000000000
#define MOD 1000000007
#define pb push_back
#define ve vector<ll>
#define dos pair<ll,ll>
#define vedos vector<dos>
#define rand mt19937 rng(chrono::steady_clock::now().time_since_epoch().count())
#define EPS 0.000001
struct greateri
{
    template<class T>
    bool operator()(T const &a, T const &b) const { return a > b; }
};
void setIO(string s) {
    ios_base::sync_with_stdio(0); cin.tie(0);
    freopen((s+".in").c_str(),"r",stdin);
    freopen((s+".out").c_str(),"w",stdout);
}
int dp[300001],dp1[300001];
string kal;
int c,n,k;
set<int>pos;
set<int>posi;
int solve(int index)
{
    int ans=1;
    auto u = pos.lower_bound(index+c+1);
    if(dp[index]!=-1)return dp[index];
    if(u!=pos.end())
    {
       ans=max(ans,1+solve((*u)));
    }
    return dp[index]=ans;
}
int solve1(int index)
{
    int ans=1;
    auto u = posi.lower_bound(-index+c+1);
    if(dp1[index]!=-1)return dp1[index];
    if(u!=pos.end() && (*u)<=0)
    {
       ans=max(ans,1+solve1(-(*u)));
    }
    return dp1[index]=ans;
}
int main()
{
  //flash;
  cin>>n>>k>>c;
  cin>>kal;
  ve kaki;
  memset(dp,-1,sizeof dp);
  memset(dp1,-1,sizeof dp1);
  for (int i = 0; i < kal.size(); ++i)
  {
      if(kal[i]=='o'){pos.insert(i);posi.insert(-i);kaki.pb(i);}
  }
  for(auto it:pos){solve(it);solve1(it);}
  int last=0;
  ve ans;
  for (int i = 0; i < kaki.size(); ++i)
  {
    int v=0;
    int s=0;
    if((i+1)>=kaki.size())s=0;
    else s = dp[kaki[i+1]];
    if((i-1)<0)v=0;
    else v = dp1[kaki[i-1]];
    if((v+s)<k)ans.pb(kaki[i]);
  }
  for(auto it:ans)cout<<it+1<<'\n';
  return 0;
}
//code the AC sol !
// BS/queue/map


#include<bits/stdc++.h>
#define ll long long int
#define ld long double
#define inf LLONG_MAX>>2
#define MAX 1000000
#define mod 1000000007
#define pb push_back
#define f(i,a,n,x) for ((i)=(a);(i)<(n);(i)+=(x))
#define fd(i,a,n,x) for ((i)=(a);(i)>=(n);(i)-=(x))
#define fi first
#define se second
#define mk make_pair
#define pi pair
#define vt vector
#define ms multiset
#define is insert
using namespace std;
void read(vt<ll> &a,ll n){ll i,temp;f(i,0,n,1){cin>>temp;a.pb(temp);}}
ll fa[MAX];
ll power(ll p,ll q){
    ll res=1;
    p%=mod;
    while(q){
        if (q&1)
            res=(res*p)%mod;
        q>>=1;
        p=(p*p)%mod;
    }
    return res;
}
ll fact(ll n){
    if (n<=1)
        return fa[n]=1;
    if (fa[n])
        return fa[n];
    return fa[n]=(n*fact(n-1))%mod;
}
ll ncr(ll n,ll r){
    if (!r)
        return 1;
    return (((fact(n)*power(fact(n-r),mod-2))%mod)*power(fact(r),mod-2))%mod;
}
void solve(){
    ll n,i,n1,count=0;
    vt<ll> a;
    cin>>n;
    if (n==2){
        cout<<1<<endl;
        return;
    }
    n1=n;
    for (i=2;i*i<=(n-1);i++)
        if (!((n-1)%i))
            if ((n-1)/i==i)
                count++;
            else
                count+=2;
    count++;
    for (i=2;i*i<=n;i++)
        if (!(n%i))
            if (n/i==i)
                a.pb(i);
            else{
                a.pb(i);
                a.pb(n/i);
            }
    a.pb(n);
    f(i,0,a.size(),1){
        n1=n;
        while(!(n1%a[i]))
            n1/=a[i];
        if (n1%a[i]==1)
            count++;
    }
    cout<<count<<endl;
}
int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    ll t=1;
    //cin>>t;
    while(t--)
        solve();
    return 0;
}

Score : 600 points

Problem Statement

Given is a positive integer N.

We will choose an integer K between 2 and N (inclusive), then we will repeat the operation below until N becomes less than K.

Operation: if K divides N, replace N with N/K; otherwise, replace N with N-K.

In how many choices of K will N become 1 in the end?

Constraints

2 \leq N \leq 10^{12}

N is an integer.

Input

Input is given from Standard Input in the following format:

N

Output

Print the number of choices of K in which N becomes 1 in the end.

Sample Input 1

6

Sample Output 1

3

There are three choices of K in which N becomes 1 in the end: 2, 5, and 6.

In each of these choices, N will change as follows:

When K=2: 6 \to 3 \to 1

When K=5: 6 \to 1

When K=6: 6 \to 1

Sample Input 2

3141

Sample Output 2

13

Sample Input 3

314159265358

Sample Output 3

9


#include<bits/stdc++.h>
using namespace std;
using ull=unsigned long long;
#define mod 1000000007
#define mod2 998244353
#define PI 3.14159265
#define ll long long
#define ld long double
#define pi pair<ll,ll>
#define pb push_back
#define vi vector<ll>
#define sz size()
#define setbits(x)  __builtin_popcount(x)
#define fi first
#define se second
#define lz length()
#define all(x) (x).begin(),(x).end()
#define scf(x) scanf("%lld",&x)
#define rep(i,n) for(ll i=0;i<n;i++)
const int INF = (int)1e9;
const ll IINF=1LL<<62;
const int maxn=10000005;

//int divr[maxn];
/**/
/*void divisor()
{for(int i=2;i<sqrt(maxn);i++)
     {
          if(!divr[i])
          {
               for(int j=i*i;j<maxn;j+=i)if(!divr[j])divr[j]=i;
          }
     }
     for(int i=1;i<maxn;i++)if(!divr[i])divr[i]=i;
}*/

/*const int N=1000005;
ll n;
struct line {
    long long m, c;
    long long eval(long long x) { return m * x + c; }
    long double intersectX(line l) { return (long double) (c - l.c) / (l.m - m); }
};
vector<pair<pi,ll>> rect;
deque<line> dq;
*/
/*int find(int a){
     if(a==par[a])return a;
     return par[a]=find(par[a]);
}
void unite(int a,int b){
     a=find(a),b=find(b);
     if(a==b)return ;
     par[b]=a;
}
ll modexpo(ll a,ll b)
{
     ll ans=1LL;
     while(b>0)
     {
          if(b&1)ans=(ans*a)%mod;
          a=(a*a)%mod;
          b>>=1;
     }
     return ans;
}
*/
int main(){
    ll n;
    cin>>n;
    int res=0;
    ll m=n-1;
    for(ll i=1LL;i<=sqrt(n);i++){
              if(n%i==0){
                   ll t=n,d=i;
                   if(i>1LL){
                   while(t%d==0)t/=d;
                   if(t%d==1)res++;
                   }
                   d=n/i;
                   t=n;
                   if(1LL*i*i!=n){
                        while(t%d==0)t/=d;
                        if(t%d==1)res++;
                   }

              }

    }
    for(int i=1LL;i<=sqrt(m);i++){
         if((m)%i==0){
              if(i>1LL)res++;
              if(1LL*i*i!=m)res++;
         }
    }
    cout<<res;
}


#include <bits/stdc++.h>

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define rrep(i, n) for(int i = ((int)(n)-1); i >= 0; i--)
#define all(x) (x).begin(),(x).end()

using namespace std;
using ll = long long;

template<class T>bool chmax(T &a, const T &b) { if (a<b) { a=b; return 1; } return 0; }
template<class T>bool chmin(T &a, const T &b) { if (b<a) { a=b; return 1; } return 0; }

struct edge { int to; int cost; };

typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> P;

const int INF = 1e9;
const int MOD = 1e9+7;
const double EPS = 1.0e-10;
const double PI = acos(-1.0);

const int mx4[] = {0,1,0,-1};
const int my4[] = {1,0,-1,0};
const int mx8[] = {0,1,1,1,0,-1,-1,-1};
const int my8[] = {1,1,0,-1,-1,-1,0,1};

int main() {
	string s;
	cin >> s;
	cout << (s[2] == s[3] && s[4] == s[5] ? "Yes" : "No") << endl;
	return 0;
}

Score : 100 points

Problem Statement

A string of length 6 consisting of lowercase English letters is said to be coffee-like if and only if its 3-rd and 4-th characters are equal and its 5-th and 6-th characters are also equal.

Given a string S, determine whether it is coffee-like.

Constraints

S is a string of length 6 consisting of lowercase English letters.

Input

Input is given from Standard Input in the following format:

S

Output

If S is coffee-like, print Yes; otherwise, print No.

Sample Input 1

sippuu

Sample Output 1

Yes

In sippuu, the 3-rd and 4-th characters are equal, and the 5-th and 6-th characters are also equal.

Sample Input 2

iphone

Sample Output 2

No

Sample Input 3

coffee

Sample Output 3

Yes


#include<bits/stdc++.h>
using namespace std;
#define ll long long
int main()
{
    string s ;
    cin>>s;
    if(s[2]==s[3]&&s[4]==s[5])
        cout<<"Yes"<<"\n";
    else
        cout<<"No"<<"\n";
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
	ios_base::sync_with_stdio(false);
    long int x;cin>>x;
  	long long int ans=(x/500)*1000;
  	x%=500;
  	ans+=5*(x/5);
  	cout<<ans<<"\n";
  return 0;
}

Score : 200 points

Problem Statement

Takahashi loves gold coins. He gains 1000 happiness points for each 500-yen coin he has and gains 5 happiness points for each 5-yen coin he has. (Yen is the currency of Japan.)

Takahashi has X yen. If he exchanges his money so that he will gain the most happiness points, how many happiness points will he earn?

(We assume that there are six kinds of coins available: 500-yen, 100-yen, 50-yen, 10-yen, 5-yen, and 1-yen coins.)

Constraints

0 \leq X \leq 10^9

X is an integer.

Input

Input is given from Standard Input in the following format:

X

Output

Print the maximum number of happiness points that can be earned.

Sample Input 1

1024

Sample Output 1

2020

By exchanging his money so that he gets two 500-yen coins and four 5-yen coins, he gains 2020 happiness points, which is the maximum number of happiness points that can be earned.

Sample Input 2

0

Sample Output 2

0

He is penniless - or yenless.

Sample Input 3

1000000000

Sample Output 3

2000000000

He is a billionaire - in yen.


//#pragma GCC optimize("O3")
//#pragma GCC target("avx")

#include <algorithm>
#include <cmath>
#include <functional>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>

using namespace std;

// Types
using ll = long long int;
using ld = long double;
using str = string;
template <class T> using u_set = unordered_set<T>;
template <class K, class V> using u_map = unordered_map<K, V>;
template <class V> using graph = u_map<V, u_set<V>>;

namespace io {
// Input
using IS = istream;
IS &in(IS &);
IS &in(IS &i) { return i; }
template <class T, class... Ts> IS &in(IS &i, T &a, Ts &... as) {
  return in(i >> a, as...);
}
template <class V> IS &operator>>(IS &i, vector<V> &a) {
  for_each(a.begin(), a.end(), [&i](auto &e) { i >> e; });
  return i;
}
template <class F, class S> IS &operator>>(IS &i, pair<F, S> &p) {
  return in(i, p.first, p.second);
}
template <class... Ts, size_t... I>
IS &tuple_in(IS &i, tuple<Ts...> &t, index_sequence<I...>) {
  return in(i, get<I>(t)...);
}
template <class... Ts> IS &operator>>(IS &i, tuple<Ts...> &t) {
  return tuple_in(i, t, make_index_sequence<sizeof...(Ts)>());
}
// Output
using OS = ostream;
OS &out(OS &o) { return o << endl; }
template <class T> OS &out(OS &o, T const &a) { return o << a << endl; }
template <class T, class... Ts> OS &out(OS &o, T const &a, Ts const &... as) {
  return out(o << a << " ", as...);
}
template <class F, class S> OS &operator<<(OS &o, pair<F, S> const &p) {
  return o << p.first << ":" << p.second;
}
template <class... Ts> OS &args_out(OS &o, Ts const &... ts);
OS &args_out(OS &o) { return o; }
template <class T> OS &args_out(OS &o, T const &t) { return o << t; }
template <class T0, class T1, class... Ts>
OS &args_out(OS &o, T0 const &t0, T1 const &t1, Ts const &... ts) {
  return args_out(o << t0 << ",", t1, ts...);
}
template <class... Ts, size_t... I>
OS &tuple_out(OS &o, tuple<Ts...> const &t, index_sequence<I...>) {
  return args_out(o, get<I>(t)...);
}
template <class... Ts> OS &operator<<(OS &o, tuple<Ts...> const &t) {
  return tuple_out(o << "(", t, make_index_sequence<sizeof...(Ts)>()) << ")";
}
template <class T> struct Joiner {
  str const pre;
  str const post;
  str const delim;
  vector<T> const container;
  Joiner(vector<T> v, str const &delim, str const &pre, str const &post)
      : pre(pre), post(post), delim(delim), container(v) {}
};
template <class T> OS &operator<<(OS &o, Joiner<T> const &joiner) {
  auto itr = joiner.container.begin();
  auto end = joiner.container.end();
  o << joiner.pre;
  if (itr != end)
    o << *(itr++);
  while (itr != end)
    o << joiner.delim << *(itr++);
  return o << joiner.post;
}
template <class Itr, class T = typename iterator_traits<Itr>::value_type>
Joiner<T> join(Itr b, Itr e, str const &delim = ""s, str const &pre = ""s,
               str const &post = ""s) {
  return Joiner<T>(vector<T>(b, e), delim, pre, post);
}
template <
    class C,
    class T = typename iterator_traits<typename C::iterator>::value_type,
    typename enable_if<!is_same<C, str>::value, nullptr_t>::type = nullptr>
OS &operator<<(OS &o, C const &a) {
  return o << join(a.begin(), a.end(), ",", "[", "]");
}
} // namespace io
auto input = [](auto &... a) { io::in(cin, a...); };
auto print = [](auto const &... a) { io::out(cout, a...); };
#ifdef JUMPAKU_DEBUG
auto dump = [](auto const &... a) { io::out(cerr, a...); };
#else
auto dump = [](auto const &...) {};
#endif
using io::join;

// Hash
namespace hashcode {
template <class... Ts> uint64_t hash_args(uint64_t h, Ts const &... ts);
uint64_t hash_args(uint64_t h) { return h; }
template <class T, class... Ts>
uint64_t hash_args(uint64_t h, T const &t, Ts const &... ts) {
  constexpr hash<T> hasher;
  return hash_args(((h << 19) - h) ^ hasher(t), ts...);
}
template <class... Ts, size_t... I>
uint64_t hash_tuple(tuple<Ts...> const &t, index_sequence<I...>) {
  return hash_args(17, get<I>(t)...);
}
} // namespace hashcode
namespace std {
template <class... Ts> struct hash<tuple<Ts...>> {
  size_t operator()(tuple<Ts...> const &t) const {
    uint64_t h = hashcode::hash_tuple(t, index_sequence_for<Ts...>());
    return h ^ (h >> 32);
  }
};
} // namespace std

// Range
namespace ranges {
template <class T, class Itr> struct iterator_base {
  using difference_type = ll;
  using value_type = T;
  using pointer = T *;
  using reference = T &;
  using iterator_category = random_access_iterator_tag;
  ll i;
  iterator_base(ll const &i = 0) : i(i) {}
  bool operator==(Itr const &itr) const { return i == itr.i; }
  bool operator!=(Itr const &itr) const { return i != itr.i; }
  ll operator-(Itr const &itr) const { return i - itr.i; }
  Itr operator++(int) { return with(i++); }
  Itr operator--(int) { return with(i--); }
  Itr operator+(ll const &n) const { return with(i + n); }
  Itr operator-(ll const &n) const { return with(i - n); }
  Itr &operator+=(ll const &n) {
    i += n;
    return self();
  }
  Itr &operator-=(ll const &n) { return self() += (-n); }
  Itr &operator++() { return self() += 1; }
  Itr &operator--() { return self() -= 1; }

protected:
  virtual Itr with(ll i) const = 0;
  virtual Itr &self() = 0;
};
template <class T> struct seq_base {
  ll const b;
  ll const e;
  seq_base(ll b, ll e) : b(b), e(e) {}
  ll size() const { return e - b; }
  bool empty() const { return size() == 0; }
};
template <class T> struct seq : seq_base<T> {
  struct iterator : iterator_base<T, iterator> {
    seq<T> const &s;
    iterator(seq<T> const &s, ll const &i)
        : iterator_base<T, iterator>(i), s(s) {}
    iterator with(ll i) const override { return iterator(s, i); }
    iterator &self() override { return *this; }
    T operator*() const { return s[this->i]; }
    iterator &operator=(iterator const &itr) {
      this->i = itr.i;
      return *this;
    }
  };
  function<T(ll)> const f;
  seq(ll b, ll e, function<T(ll)> const &f) : seq_base<T>(b, e), f(f) {}
  iterator begin() const { return iterator(*this, 0); }
  iterator end() const { return iterator(*this, this->size()); }
  T operator[](ll i) const { return f(i + this->b); }
};
struct range : seq_base<ll> {
  struct iterator : iterator_base<ll, iterator> {
    iterator(ll const &i) : iterator_base<ll, iterator>(i) {}
    iterator with(ll i) const override { return iterator(i); }
    iterator &self() override { return *this; }
    ll operator*() const { return i; }
  };
  range(ll n) : range(0LL, n) {}
  range(ll b, ll e) : seq_base<ll>(b, e) {}
  iterator begin() const { return iterator(b); }
  iterator end() const { return iterator(e); }
  ll operator[](ll i) const { return i + b; }
};
} // namespace ranges
using range = ranges::range;
range::iterator end(ll i) { return range::iterator(i); }
range::iterator begin(ll i) { return range::iterator(i); }
template <class F> auto seq(ll b, ll e, F const &f) {
  using T = decltype(f(declval<ll>()));
  return ranges::seq<T>(b, e, f);
}
template <class F> auto seq(ll n, F const &f) { return seq(0, n, f); }
template <class T = ll> vector<T> vec(size_t n, T const &init = T()) {
  return vector<T>(n, init);
}

ll gcd(ll p, ll q) { return (q == 0) ? p : gcd(q, p % q); }
ll lcm(ll p, ll q) { return p / gcd(q, p) * q; }
bool odd(ll n) { return n & 1; }
bool even(ll n) { return !odd(n); }

constexpr ll MOD = 1e9 + 7;

void solve();
int main() {
  ll t = 1;
  /** input(t); /**/
  for ([[maybe_unused]] auto &&i : range(t)) {
    solve();
  }
}

void solve() {
  ll X;
  input(X);
  ll a = X / 500;
  ll b = (X % 500) / 5;
  print(1000 * a + 5 * b);
}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int k,n;
  cin>>k>>n;
  vector<int> a(n);
  for(int i=0; i<n; i++){
    cin>>a.at(i);
  }
  int ans;
  if((a.at(n-1)-a.at(1))>=20-a.at(n-1)+a.at(1)){
    ans=a.at(1)+20-a.at(n-1);
  }
  else ans=a.at(n-1)-a.at(0);

  cout<<ans<<endl;
}

Score : 300 points

Problem Statement

There is a circular pond with a perimeter of K meters, and N houses around them.

The i-th house is built at a distance of A_i meters from the northmost point of the pond, measured clockwise around the pond.

When traveling between these houses, you can only go around the pond.

Find the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Constraints

2 \leq K \leq 10^6

2 \leq N \leq 2 \times 10^5

0 \leq A_1 < ... < A_N < K

All values in input are integers.

Input

Input is given from Standard Input in the following format:

K N
A_1 A_2 ... A_N

Output

Print the minimum distance that needs to be traveled when you start at one of the houses and visit all the N houses.

Sample Input 1

20 3
5 10 15

Sample Output 1

10

If you start at the 1-st house and go to the 2-nd and 3-rd houses in this order, the total distance traveled will be 10.

Sample Input 2

20 3
0 5 15

Sample Output 2

10

If you start at the 2-nd house and go to the 1-st and 3-rd houses in this order, the total distance traveled will be 10.


#include <bits/stdc++.h>
using namespace std;
const int N=2005;
int n,x,y;
int cnt[N];
int main() {
	int i,j;
	cin>>n>>x>>y;
	for (i=1;i<n;i++)
		for (j=i+1;j<=n;j++) {
			if (i<x&&j<x) cnt[j-i]++;
			else if (i>y&&j>y) cnt[j-i]++;
			else if (i<x&&j>y) cnt[j-y+x-i+1]++;
			else if (i<x&&j>=x) cnt[min(j-i,y-j+1+x-i)]++;
			else if (i<=y&&j>y) cnt[min(j-i,i-x+1+j-y)]++;
			else cnt[min(j-i,i-x+y-j+1)]++;
//			cout<<i<<' '<<j<<' '<<cnt[1]<<endl;
		}
	for (i=1;i<=n-1;i++) cout<<cnt[i]<<endl;
	return 0;
}

Score : 400 points

Problem Statement

We have an undirected graph G with N vertices numbered 1 to N and N edges as follows:

For each i=1,2,...,N-1, there is an edge between Vertex i and Vertex i+1.

There is an edge between Vertex X and Vertex Y.

For each k=1,2,...,N-1, solve the problem below:

Find the number of pairs of integers (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j in G is k.

Constraints

3 \leq N \leq 2 \times 10^3

1 \leq X,Y \leq N

X+1 < Y

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N X Y

Output

For each k=1, 2, ..., N-1 in this order, print a line containing the answer to the problem.

Sample Input 1

5 2 4

Sample Output 1

5
4
1
0

The graph in this input is as follows:

There are five pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 1: (1,2)\,,(2,3)\,,(2,4)\,,(3,4)\,,(4,5).

There are four pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 2: (1,3)\,,(1,4)\,,(2,5)\,,(3,5).

There is one pair (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 3: (1,5).

There are no pairs (i,j) (1 \leq i < j \leq N) such that the shortest distance between Vertex i and Vertex j is 4.

Sample Input 2

3 1 3

Sample Output 2

3
0

The graph in this input is as follows:

Sample Input 3

7 3 7

Sample Output 3

7
8
4
2
0
0

Sample Input 4

10 4 8

Sample Output 4

10
12
10
8
4
1
0
0
0


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD = 1e9 + 7;
const int inf = 1e9;
const ll INF = 1e18;
const double pi = 3.14159265358979323846;
#define rep(i,n) for(ll i=0;i<n;i++)

int main(){
	int n;cin>>n;
	int x,y;cin>>x>>y;
	x--;y--;
	int ans[n+1]={};
	for(int i=0;i<n-1;i++){
		for(int j=i+1;j<n;j++){
			int sum=abs(x-i)+abs(y-j)+1;
			ans[min(sum,j-i)]++;
			//cout<<i+1<<" "<<j+1<<" : "<<min(sum,j-i)<<"\n";
		}
	}

	for(int i=1;i<n;i++) cout<<ans[i]<<"\n";
}


#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <list>
#include <deque>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
#include <algorithm>
#include <cmath>
#define ll long long
#define INF 0x3f3f3f3f
#define SIS std::ios::sync_with_stdio(false)
using namespace std;
ll fast_pow(ll a,ll b,ll mod)
{
    ll c=1;
    while(b>=2)
    {
        if(b%2==0)
            a*=a,b/=2;
        else
            c*=a,a*=a,b--,b/=2;
        a%=mod,c%=mod;
    }
    return (a*c)%mod;
}
ll cal(ll n,ll m);
int main()
{
    int n,m;
    while(cin>>n>>m)
    {
        ll ans=0;
        if(n>1)
            ans+=cal(n,2);
        if(m>1)
            ans+=cal(m,2);
        cout<<ans<<endl;
    }
    return 0;
}

ll cal(ll n,ll m)
{
    return n*(n-1)/2;
}

Score : 100 points

Problem Statement

We have N+M balls, each of which has an integer written on it.

It is known that:

The numbers written on N of the balls are even.

The numbers written on M of the balls are odd.

Find the number of ways to choose two of the N+M balls (disregarding order) so that the sum of the numbers written on them is even.

It can be shown that this count does not depend on the actual values written on the balls.

Constraints

0 \leq N,M \leq 100

2 \leq N+M

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N M

Output

Print the answer.

Sample Input 1

2 1

Sample Output 1

1

For example, let us assume that the numbers written on the three balls are 1,2,4.

If we choose the two balls with 1 and 2, the sum is odd;

If we choose the two balls with 1 and 4, the sum is odd;

If we choose the two balls with 2 and 4, the sum is even.

Thus, the answer is 1.

Sample Input 2

4 3

Sample Output 2

9

Sample Input 3

1 1

Sample Output 3

0

Sample Input 4

13 3

Sample Output 4

81

Sample Input 5

0 3

Sample Output 5

3


#include <bits/stdc++.h>
#define rep(i,n) for (int i=0;i<(n);i++)
#define adrep(i,s,n) for (int i=(s);i<(n);i++)
using namespace std;
typedef long long ll;

int check(string t){

  int n=t.length();
  rep(i,n){
    //cout<<t[i]<<" "<<t[n-(i+1)]<<endl;
    if(t[i]!=t[n-(i+1)]){
      return 0;
    }
  }
  return 1;
}

int main(){

 string s;

  cin>>s;

  int N=s.length();

  if(check(s)==0){cout<<"No"<<endl;return 0;}
  string s1=s.substr(0,(N-1)/2);
  //cout<<s1<<endl;
  if(check(s1)==0){cout<<"No"<<endl;return 0;}
  string s2=s.substr((N+3)/2-1,(N-1)/2);
  //cout<<s2<<endl;
  if(check(s2)==0){cout<<"No"<<endl;return 0;}

  cout<<"Yes"<<endl;
}

Score : 200 points

Problem Statement

A string S of an odd length is said to be a strong palindrome if and only if all of the following conditions are satisfied:

S is a palindrome.

Let N be the length of S. The string formed by the 1-st through ((N-1)/2)-th characters of S is a palindrome.

The string consisting of the (N+3)/2-st through N-th characters of S is a palindrome.

Determine whether S is a strong palindrome.

Constraints

S consists of lowercase English letters.

The length of S is an odd number between 3 and 99 (inclusive).

Input

Input is given from Standard Input in the following format:

S

Output

If S is a strong palindrome, print Yes;
otherwise, print No.

Sample Input 1

akasaka

Sample Output 1

Yes

S is akasaka.

The string formed by the 1-st through the 3-rd characters is aka.

The string formed by the 5-th through the 7-th characters is aka.
All of these are palindromes, so S is a strong palindrome.

Sample Input 2

level

Sample Output 2

No

Sample Input 3

atcoder

Sample Output 3

No


#include <iostream>
using namespace std;
#define int long long
signed main() {
	string s;
	cin>>s;
	int n=s.size();
	int i=0;
	int j=s.size()-1;
	while(i<j)
	{
	    if(s[i]!=s[j])
	    break;
	    i++;
	    j--;
	}
	if(i!=j)
	{
	    cout<<"No"<<endl;
	    return 0;
	}
	j=(n-1)/2-1;
	i=0;
	while(i<j)
	{
	    if(s[i]!=s[j])
	    {
	        cout<<"No";
	        return 0;
	    }
	    i++;
	    j--;
	}
	cout<<"Yes";
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
using P = pair<ll,ll>;
const ll mod = 1e9+7;
#define ALL(x) (x).begin(),(x).end()
#define pow(x,y) modpow(x,y)
#define REP(i,n) for(ll (i)=0;(i)<(n);(i)++)

template <class T = int>T in(){
    T x;
    cin >> x;
    return (x);
}

signed main(){
    cin.tie(0);
    ios::sync_with_stdio(false);
    cout<<fixed<<setprecision(10);
    string S = in<string>();
    bool ok = 1;
    int N = S.size();
    REP(i,N/2)if(S[i] != S[N-1-i])ok = 0;
    REP(i,(N/2)/2)if(S[i] != S[N/2-1-i])ok = 0;
    REP(i,(N/2)/2)if(S[N-1-i] != S[N/2+1-i])ok = 0;
    cout << (ok ? "Yes" : "No") << "\n";
}


#include <bits/stdc++.h>
using namespace std;

int main(){
  int L;
  cin >> L;

  double count=L*L*L/27;
  cout << fixed << setprecision(15) << count << endl;
}

Score : 300 points

Problem Statement

Given is a positive integer L.
Find the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.

Constraints

1 ≤ L ≤ 1000

L is an integer.

Input

Input is given from Standard Input in the following format:

L

Output

Print the maximum possible volume of a rectangular cuboid whose sum of the dimensions (not necessarily integers) is L.
Your output is considered correct if its absolute or relative error from our answer is at most 10^{-6}.

Sample Input 1

3

Sample Output 1

1.000000000000

For example, a rectangular cuboid whose dimensions are 0.8, 1, and 1.2 has a volume of 0.96.

On the other hand, if the dimensions are 1, 1, and 1, the volume of the rectangular cuboid is 1, which is greater.

Sample Input 2

999

Sample Output 2

36926037.000000000000


#include<bits/stdc++.h>
using namespace std;

int main()
{
    int l;
    cin>>l;
    float f=l/3.0;
    cout<<fixed << setprecision(6) <<f*f*f;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

#define F(i,a,b) for(long long  i =a; i<b; i++)
#define rF(i,a,b) for(long long i=a-1; i>=b;i--)
#define endl "\n"
#define min1(x,y,z) min(x, min(y,z))
#define max1(x,y,z) max(x, max(y,z))
#define input_vector(v,n,type) vector<type> v;for(int i=0;i<n;i++){type x;cin>>x;v.push_back(x);}
#define IOS ios_base::sync_with_stdio(false);  cin.tie(NULL);  cout.tie(NULL);
#define int long long
#define inf (1LL<<61)
typedef pair<int,int> ii;
typedef vector<pair<int,int>> vii;
typedef vector<int> vi;

int32_t main()
{
        IOS;

        int L;
        cin>>L;

        if (L == 1) {
                double ans = (double)1/(double)27;
                cout<<fixed<<setprecision(10)<<ans<<endl;
                return 0;
        }
        if (L == 2) {
                double ans = (double)8/(double)27;
                cout<<fixed<<setprecision(10)<<ans<<endl;
                return 0;
        }
        if (true) {
                double x = (double)L/(double)3;
                double ans = x*x*x;
                cout<<fixed<<setprecision(10)<<ans<<endl;
        } else if (L%3 == 1) {
                double ans = (L/3*(L+1)/3*L/3);
                cout<<fixed<<setprecision(10)<<ans<<endl;
        } else {
                double ans = (L/3*(L+1)/3*(L+1)/3);
                cout<<fixed<<setprecision(10)<<ans<<endl;
        }

        return 0;
}


#include "./bits/stdc++.h"

using namespace std;

int main() {
    int N;
    vector<int> A;

    cin >> N;
    for (int i = 0; i < N; i++) {
        int tmp;
        cin >> tmp;
        A.emplace_back(tmp);
    }

    int count_box[int(2e5) + 1];
    vector<int> memo;

    for (int i = 0; i < N; i++) {
        if (count_box[A[i]] == 0) memo.emplace_back(A[i]);
        count_box[A[i]]++;
    }

    long long total = 0;
    for (auto& v : memo) total += count_box[v] * (count_box[v] - 1) / 2;

    for (int i = 0; i < N; i++) {
        long long result = total - count_box[A[i]] + 1;
        cout << result << endl;
    }
}

Score : 400 points

Problem Statement

We have N balls. The i-th ball has an integer A_i written on it.

For each k=1, 2, ..., N, solve the following problem and print the answer.

Find the number of ways to choose two distinct balls (disregarding order) from the N-1 balls other than the k-th ball so that the integers written on them are equal.

Constraints

3 \leq N \leq 2 \times 10^5

1 \leq A_i \leq N

All values in input are integers.

Input

Input is given from Standard Input in the following format:

N
A_1 A_2 ... A_N

Output

For each k=1,2,...,N, print a line containing the answer.

Sample Input 1

5
1 1 2 1 2

Sample Output 1

2
2
3
2
3

Consider the case k=1 for example. The numbers written on the remaining balls are 1,2,1,2.

From these balls, there are two ways to choose two distinct balls so that the integers written on them are equal.

Thus, the answer for k=1 is 2.

Sample Input 2

4
1 2 3 4

Sample Output 2

0
0
0
0

No two balls have equal numbers written on them.

Sample Input 3

5
3 3 3 3 3

Sample Output 3

6
6
6
6
6

Any two balls have equal numbers written on them.

Sample Input 4

8
1 2 1 4 2 1 4 1

Sample Output 4

5
7
5
7
7
5
7
5


/*
    アリナ・グレイはかわいい
*/

#include<bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<int,int>;
#define itn int
#define endl "\n"

int main(void){
    int h,w,k;
    cin >> h >> w >> k;
    string s[1004];
    int mn = 1LL<<30;

    for(int i = 0;i < h;i++)cin >> s[i];

    for(int i = 0;i < (1 << (h-1));i++){
        int sum = 0,a[100] = {};
        for(int j = 0;j < h;j++){
            a[j] = sum;
            if(i & (1 << j))sum++;
        }
        sum++;
        int num = __builtin_popcount(i),b[100] = {};

        //for(int p = 0;p < h;p++)b[p] = 0;
        for(int p = 0;p < w;p++){
            for(int q = 0;q < h;q++){
                b[a[q]] += (s[q][p]-'0');
            }
            for(int q = 0;q < sum;q++){
                if(b[q] > k){
                    num++;
                    for(int l = 0;l < sum;l++)b[l] = 0;
                    for(int l = 0;l < h;l++)b[a[l]] += (s[l][p]-'0');
                    break;
                }
            }
            for(int l = 0;l < num;l++)if(b[l] > k)num = 1LL<<30;
        }
        mn = min(mn,num);
    }
    cout << mn << endl;
}

Score : 500 points

Problem Statement

We have a chocolate bar partitioned into H horizontal rows and W vertical columns of squares.

The square (i, j) at the i-th row from the top and the j-th column from the left is dark if S_{i,j} is 0, and white if S_{i,j} is 1.

We will cut the bar some number of times to divide it into some number of blocks. In each cut, we cut the whole bar by a line running along some boundaries of squares from end to end of the bar.

How many times do we need to cut the bar so that every block after the cuts has K or less white squares?

Constraints

1 \leq H \leq 10

1 \leq W \leq 1000

1 \leq K \leq H \times W

S_{i,j} is 0 or 1.

Input

Input is given from Standard Input in the following format:

H W K
S_{1,1}S_{1,2}...S_{1,W}
:
S_{H,1}S_{H,2}...S_{H,W}

Output

Print the number of minimum times the bar needs to be cut so that every block after the cuts has K or less white squares.

Sample Input 1

3 5 4
11100
10001
00111

Sample Output 1

2

For example, cutting between the 1-st and 2-nd rows and between the 3-rd and 4-th columns - as shown in the figure to the left - works.

Note that we cannot cut the bar in the ways shown in the two figures to the right.

Sample Input 2

3 5 8
11100
10001
00111

Sample Output 2

0

No cut is needed.

Sample Input 3

4 10 4
1110010010
1000101110
0011101001
1101000111

Sample Output 3

3


#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for(int i=(a);i<(b);++i)
#define rep(i, n) FOR(i, 0, n)
#define whole(x) (x).begin(),(x).end()
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end())
using ll = long long;
using P = pair<int, int>;
const int mod = 1000000007;
const int INF = 1001001001;
int sum[11][1005];

int main(){
    int h, w, k;
    cin >> h >> w >> k;
    vector<string> s(h);
    rep(i, h) {
        cin >> s[i];
    }
    rep(i, h) rep(j, w) {
        sum[i][j+1] = sum[i][j] + (s[i][j]-'0');
    }

    int ans = INF;
    rep(i, 1<<(h-1)) {
        int res = __builtin_popcount(i);
        int st = 0;
        int temp = 0;
        rep(j, w) rep(l, h) {
            temp += (sum[l][j+1] - sum[l][st]);
            if (i>>l&1 || l==h-1) {
                if (temp>k) {
                    st = j;
                    res++;
                    l = 0;
                }
                temp = 0;

            }
        }

        ans = min(ans, res);
    }

    cout << ans << endl;
    return 0;
}


#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int main(){
	int h,w;
	cin>>h>>w;
	char ptr[150][150];
	int dp[150][150];
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			cin>>ptr[i][j];
		}
	}
	memset(dp,0x3f,sizeof(dp));
	dp[1][1]=(ptr[1][1]=='#');
	for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			if(ptr[i][j+1]=='.'){//下一步，代表不要变
				dp[i][j+1]=min(dp[i][j+1],dp[i][j]);
			}else{//下一步代表要变
				dp[i][j+1]=min(dp[i][j+1],dp[i][j]+(ptr[i][j]=='.'));
			}
			if(ptr[i+1][j]=='.'){//下一步代表不要变
				dp[i+1][j]=min(dp[i+1][j],dp[i][j]);
			}else{//下一步代表要变
				dp[i+1][j]=min(dp[i+1][j],dp[i][j]+(ptr[i][j]=='.'));
			}
		}
	}
	cout<<dp[h][w]<<endl;
	return 0;
}

Score : 400 points

Problem Statement

Consider a grid with H rows and W columns of squares. Let (r, c) denote the square at the r-th row from the top and the c-th column from the left.
Each square is painted black or white.

The grid is said to be good if and only if the following condition is satisfied:

From (1, 1), we can reach (H, W) by moving one square right or down repeatedly, while always being on a white square.

Note that (1, 1) and (H, W) must be white if the grid is good.

Your task is to make the grid good by repeating the operation below. Find the minimum number of operations needed to complete the task. It can be proved that you can always complete the task in a finite number of operations.

Choose four integers r_0, c_0, r_1, c_1(1 \leq r_0 \leq r_1 \leq H, 1 \leq c_0 \leq c_1 \leq W). For each pair r, c (r_0 \leq r \leq r_1, c_0 \leq c \leq c_1), invert the color of (r, c) - that is, from white to black and vice versa.

Constraints

2 \leq H, W \leq 100

Input

Input is given from Standard Input in the following format:

H W
s_{11} s_{12} \cdots s_{1W}
s_{21} s_{22} \cdots s_{2W}
\vdots
s_{H1} s_{H2} \cdots s_{HW}

Here s_{rc} represents the color of (r, c) - # stands for black, and . stands for white.

Output

Print the minimum number of operations needed.

Sample Input 1

3 3
.##
.#.
##.

Sample Output 1

1

Do the operation with (r_0, c_0, r_1, c_1) = (2, 2, 2, 2) to change just the color of (2, 2), and we are done.

Sample Input 2

2 2
#.
.#

Sample Output 2

2

Sample Input 3

4 4
..##
#...
###.
###.

Sample Output 3

0

No operation may be needed.

Sample Input 4

5 5
.#.#.
#.#.#
.#.#.
#.#.#
.#.#.

Sample Output 4

4


#include <bits/stdc++.h>
#include <unistd.h>
#include <sys/time.h>
#include <stdlib.h>

using namespace std;

typedef long long ll;
typedef pair<ll,ll> P;
typedef pair<P, ll> T;

long long int INF = 1e18;
const ll fact_table = 800008;
double Pi = 3.1415926535897932384626;

priority_queue <ll> pql;
priority_queue <P> pqp;
priority_queue <P> bag;
//big priority queue
priority_queue <ll,vector<ll>,greater<ll> > pqls;
priority_queue <P,vector<P>,greater<P> > pqps;
//small priority queue
//top pop

ll dx[8]={1,0,-1,0,1,1,-1,-1};
ll dy[8]={0,1,0,-1,1,-1,-1,1};
char dir[] = "DRUL";
//↓,→,↑,←

#define p(x) cout<<x<<"\n";
#define el cout<<endl;
#define pe(x) cout<<(x)<<" ";
#define ps(x) cout<<fixed<<setprecision(25)<<x<<endl;
#define pu(x) cout<<(x);
#define pb push_back
// #define lb lower_bound
#define ub upper_bound
#define CLEAR(a) a = decltype(a)();
#define pc(x) cout << x << ",";

ll mod = 998244353;
// ll mod = 1000000007;

ll mypow(ll number1,ll number2, ll mod){

    if(number2 == 0){
        return 1;
    }else{
        ll number3 = mypow(number1,number2 / 2, mod);
        number3 *= number3;
        number3 %= mod;
        if(number2%2==1){
            number3 *= number1;
            number3 %= mod;
        }
        return number3;
    }
}
ll rui(ll number1,ll number2){

    if(number2 == 0){
        return 1;
    }else{
        ll number3 = rui(number1,number2 / 2);
        number3 *= number3;
        number3 %= mod;
        if(number2%2==1){
            number3 *= number1;
            number3 %= mod;
        }
        return number3;
    }
}
ll gcd(ll number1,ll number2){

    if(number1 > number2){
        swap(number1,number2);
    }
    if(number1 == 0 || number1 == number2){
        return number2;
    }else{
        return gcd(number2 % number1,number1);
    }
}
void YES(bool condition){

    if(condition){
        p("YES");
    }else{
        p("NO");
    }
    return;
}
void Yes(bool condition){

    if(condition){
        p("Yes");
    }else{
        p("No");
    }
    return;
}

/*
ll fact[fact_table + 5],rfact[fact_table + 5];

void c3_init(){
    fact[0] = rfact[0] = 1;
    for(ll i=1; i<=fact_table; i++){
        fact[i] = (fact[i-1]*i) % mod;
    }
    rfact[fact_table] = rui(fact[fact_table],mod - 2);
    for(ll i=fact_table; i>=1; i--){
       rfact[i-1] = rfact[i] * i;
       rfact[i-1] %= mod;
    }
    return;}
ll c3(ll n,ll r){
    return (((fact[n] * rfact[r]) % mod ) * rfact[n-r]) % mod;}
*/
bool multicase = false;

ll n,m,num,sum,a,b,c,d,e,h,q,p;
ll w, ans;
ll k;
char s[105][105];
vector<P> G[500005];
ll cost[100005];

void solve(){
    cin >> h >> w;
    for(ll i=0;i<h;i++){
        cin >> s[i];
    }
    for(ll i=0;i<h;i++){
        for(ll j=0;j<w;j++){
            ll x = i, y = j;
            for(ll k=0;k<2;k++){
                ll nx = i + dx[k], ny = j + dy[k];
                if(nx < 0 || ny < 0 || nx >= h || ny >= w)continue;
                ll fromid = i * w + j;
                ll toid = nx * w + ny;
                if(s[x][y] == s[nx][ny]){
                    G[fromid].pb(P(toid, 0));
                }else{
                    G[fromid].pb(P(toid, 1));
                }
            }
        }
    }
    ll c1 = 0, c2 = 0;
    if(s[0][0] == '#')c1++;
    if(s[h-1][w-1] == '#')c2++;
    G[h*w].pb(P(0, c1));
    G[h*w-1].pb(P(h*w+1, c2));
    for(ll i=0;i<h*w+10;i++){
        cost[i] = INF;
    }
    cost[h*w] = 0;
    pqps.push(P(0, h*w));
    while(!pqps.empty()){
        P p = pqps.top();
        pqps.pop();
        ll v = p.second;
        ll nowcost = p.first;
        if(nowcost > cost[v])continue;
        for(ll i=0;i<G[v].size();i++){
            ll nv = G[v][i].first;
            ll newcost = cost[v] + G[v][i].second;
            if(cost[nv] > newcost){
                cost[nv] = newcost;
                pqps.push(P(newcost, nv));
            }

        }
    }
    ll ans = cost[h*w+1];
    p(ans / 2);
    return;
}

int main(){
    // init();
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    ll q;
    if(multicase){
        cin >> q;
    }else{
        q = 1;
    }
    while(q--){
        solve();
    }
    return 0;

}


#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define Reg register
#define RI Reg int
#define Con const
#define CI Con int&
#define I inline
#define W while
#define N 1000000
using namespace std;
int n,a[N+5];char s[N+5];
int main()
{
	RI i;for(scanf("%d%s",&n,s),--n,i=0;i^n;++i) a[i]=abs(s[i]-s[i+1]);
	RI f=1;for(i=0;i^n;++i) if(a[i]==1) {f=0;break;}
	for(i=0;i^n;++i) a[i]==2&&(a[i]=f);
	RI ans=0;for(i=0;i^n;++i) (((n-1)^i)==(n-1)-i)&&(ans^=a[i]);
	return printf("%d",ans*(f+1)),0;
}

Score : 700 points

Problem Statement

Given is a sequence of N digits a_1a_2\ldots a_N, where each element is 1, 2, or 3.
Let x_{i,j} defined as follows:

x_{1,j} := a_j \quad (1 \leq j \leq N)

x_{i,j} := | x_{i-1,j} - x_{i-1,j+1} | \quad (2 \leq i \leq N and 1 \leq j \leq N+1-i)

Find x_{N,1}.

Constraints

2 \leq N \leq 10^6

a_i = 1,2,3 (1 \leq i \leq N)

Input

Input is given from Standard Input in the following format:

N
a_1a_2\ldotsa_N

Output

Print x_{N,1}.

Sample Input 1

4
1231

Sample Output 1

1

x_{1,1},x_{1,2},x_{1,3},x_{1,4} are respectively 1,2,3,1.

x_{2,1},x_{2,2},x_{2,3} are respectively |1-2| = 1,|2-3| = 1,|3-1| = 2.

x_{3,1},x_{3,2} are respectively |1-1| = 0,|1-2| = 1.

Finally, x_{4,1} = |0-1| = 1, so the answer is 1.

Sample Input 2

10
2311312312

Sample Output 2

0


#include <iostream>
using namespace std;

int main() {
	long long h,w;cin >>h>>w;
	long long out =1;
	if(h>1 && w>1){
		out= (h/2 + h%2)*(w/2 + w%2) + (h/2)*(w/2);
	}
	cout << out << endl;
	return 0;
}

Score : 200 points

Problem Statement

We have a board with H horizontal rows and W vertical columns of squares.
There is a bishop at the top-left square on this board.
How many squares can this bishop reach by zero or more movements?

Here the bishop can only move diagonally.
More formally, the bishop can move from the square at the r_1-th row (from the top) and the c_1-th column (from the left) to the square at the r_2-th row and the c_2-th column if and only if exactly one of the following holds:

r_1 + c_1 = r_2 + c_2

r_1 - c_1 = r_2 - c_2

For example, in the following figure, the bishop can move to any of the red squares in one move:

Constraints

1 \leq H, W \leq 10^9

All values in input are integers.

Input

Input is given from Standard Input in the following format:

H \ W

Output

Print the number of squares the bishop can reach.

Sample Input 1

4 5

Sample Output 1

10

The bishop can reach the cyan squares in the following figure:

Sample Input 2

7 3

Sample Output 2

11

The bishop can reach the cyan squares in the following figure:

Sample Input 3

1000000000 1000000000

Sample Output 3

500000000000000000


#include <iostream>
#include <algorithm>
using namespace std;

int main() {
  long long H, W;
  cin >> H >> W;
  double ans = ((H+1)/2)*((W+1)/2)+(H/2)*(W/2);
  cout << long(ans) << endl;
}


#include <bits/stdc++.h>
//上記が使用不可な環境において
/*
#include <iostream> // cout, endl, cin
#include <string> // string, to_string, stoi
#include <iomanip>  //setprecsion
#include <vector> // vector
#include <algorithm> // min, max, swap, sort, reverse, lower_bound, upper_bound
#include <utility> // pair, make_pair
#include <cmath>  //sin, cos, tan
#include <tuple> // tuple, make_tuple
#include <cstdint> // int64_t, int*_t
#include <cstdio> // printf
#include <map> // map
#include <queue> // queue, priority_queue
#include <set> // set
#include <stack> // stack
#include <deque> // deque
#include <unordered_map> // unordered_map
#include <unordered_set> // unordered_set
#include <bitset> // bitset
#include <cctype> // isupper, islower, isdigit, toupper, tolower
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <complex>
#include <bitset>
#include <utility>
#include <functional>
*/
using namespace std;

typedef long long int ll;
typedef long long int lli;
typedef unsigned long long int ull;
typedef long double ld;
typedef string str;
typedef vector<char> vc;
typedef vector<bool> vb;
typedef vector<ld> vd;
typedef vector<str> vs;
typedef vector<ll> vll;
typedef vector<pair<ll, ll>> vpll;
typedef vector<vector<ll>> vvll;
typedef vector<vector<char>> vvc;
typedef vector<vector<str>> vvs;
const ld PI = acos(-1.0);
const ll MAX = 9000000000000000000;
const ll MIN = -9000000000000000000;
const ld DMAX = 4500;
const ld DMIN = -4500;

//謎
const int INF = INT_MAX;
const ll LLINF = 1LL << 60;
const ll MOD = 1000000007;
const ld EPS = 1e-9;
ll dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
ll dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};

//0~nの範囲操作
#define rep(i, n) for (ll i = 0; i < (n); ++i)
//1~nの範囲操作
#define rrep(i, n) for (ll i = 1; i <= (n); ++i)
#define irep(it, stl) for (auto it = stl.begin(); it != stl.end(); it++)
#define drep(i, n) for (ll i = (n)-1; i >= 0; --i)
//出力後改行を
#define fin(ans) cout << (ans) << endl;
//出力後空白を
#define blank(ans) cout << (ans) << " ";
#define mp(p, q) make_pair(p, q)
#define pb(n) push_back(n)
//配列全操作
#define all(a) a.begin(), a.end()

//配列の合計
template <typename T>
T Sum(vector<T> n, ll a = 0, ll b = 0)
{
  if (b == 0)
  {
    return (accumulate(n.begin() + a, n.end(), 0));
  }
  else
  {
    return (accumulate(n.begin() + a, n.begin() + b, 0));
  }
}
template <>
ld Sum(vector<ld> n, ll a, ll b)
{
  if (b == 0)
  {
    return (accumulate(n.begin() + a, n.end(), 0));
  }
  else
  {
    return (accumulate(n.begin() + a, n.begin() + b, 0));
  }
}
//配列を昇順
template <typename T>
void Sort(T &n, ll a = 0, ll b = 0)
{
  if (b == 0)
  {
    return (sort(n.begin() + a, n.end()));
  }
  else
  {
    return (sort(n.begin() + a, n.begin() + b));
  }
}
//配列を降順
template <typename T>
void Reve(T &n, ll a = 0, ll b = 0)
{
  if (b == 0)
  {
    return (reverse(n.begin() + a, n.end()));
  }
  else
  {
    return (reverse(n.begin() + a, n.begin() + b));
  }
}
//配列nをmにコピー
template <typename T, typename U>
void Copy(T &n, U &m, ll a = 0, ll b = 0)
{
  copy(all(n), m.begin());
}
//小数点型に
template <typename T>
ld Cast(T n)
{
  return static_cast<ld>(n);
}
//配列入力
template <typename T>
void V(T &n)
{
  for (ll i = 0; i < n.size(); i++)
  {
    cin >> n[i];
  }
}
//２列配列入力
template <typename T, typename U>
void V2(T &n, U &m)
{
  for (ll i = 0; i < n.size(); i++)
  {
    cin >> n[i] >> m[i];
  }
}
//３列配列入力
template <typename T, typename U, typename W>
void V3(T &n, U &m, W &p)
{
  for (ll i = 0; i < n.size(); i++)
  {
    cin >> n[i] >> m[i] >> p[i];
  }
}
//yes, noと表示
void yn(bool a)
{
  if (a)
    cout << "yes" << endl;
  else
    cout << "no" << endl;
}
//Yes, Noと表示
void Yn(bool a)
{
  if (a)
    cout << "Yes" << endl;
  else
    cout << "No" << endl;
}
//YES, NOと表示
void YN(bool a)
{
  if (a)
    cout << "YES" << endl;
  else
    cout << "NO" << endl;
}
//yes, noと表示後終了
void fyn(bool a)
{
  if (a)
    cout << "yes" << endl;
  else
    cout << "no" << endl;
  exit(0);
}
//Yes, Noと表示後終了
void fYn(bool a)
{
  if (a)
    cout << "Yes" << endl;
  else
    cout << "No" << endl;
  exit(0);
}
//YES, NOと表示後終了
void fYN(bool a)
{
  if (a)
    cout << "YES" << endl;
  else
    cout << "NO" << endl;
  exit(0);
}
//AC, WAと表示
void AC(bool a)
{
  if (a)
    cout << "AC" << endl;
  else
    cout << "WA" << endl;
}
//AC, WAと表示後終了
void fAC(bool a)
{
  if (a)
    cout << "AC" << endl;
  else
    cout << "WA" << endl;
  exit(0);
}
//noneと表示後終了
void fnone(void)
{
  cout << "None" << endl;
  exit(0);
}
//Odd(奇数), Even(偶数)と表示後終了
void fOdd(bool a)
{
  if (a)
    cout << "Odd" << endl;
  else
    cout << "Even" << endl;
  exit(0);
}
//Possible, Impossibleと表示後終了
void Possible(bool a)
{
  if (a)
    cout << "Possible" << endl;
  else
    cout << "Impossible" << endl;
  exit(0);
}
//POSSIBLE, IMPOSSIBLEと表示後終了
void POSSIBLE(bool a)
{
  if (a)
    cout << "POSSIBLE" << endl;
  else
    cout << "IMPOSSIBLE" << endl;
  exit(0);
}
//四角　表示文字 a 縦幅 h 横幅 w
void square(char a, ll h, ll w)
{
  for (ll i = 0; i < h; i++)
  {
    for (ll j = 0; j < w; j++)
    {
      cout << a;
    }
    cout << endl;
  }
}
//四角枠　外周 a 中身 b 縦幅 h 横幅 w
void yoke(char a, char b, ll h, ll w)
{
  for (ll i = 0; i < h; i++)
  {
    for (ll j = 0; j < w; j++)
    {
      if (i == 0 || i == h - 1)
        cout << a;
      else if (j == 0 || j == w - 1)
        cout << a;
      else
        cout << b;
    }
    cout << endl;
  }
}
//四捨五入
ll C45(ll n)
{
  return (n + 1) / 2;
}
//文字列からcを探す
ll stcount(str s, char c)
{
  return count(s.cbegin(), s.cend(), c);
}
//素数
bool IsPrime(ll num)
{
  if (num < 2)
    return false;
  else if (num == 2)
    return true;
  else if (num % 2 == 0)
    return false;
  ld sqrtNum = sqrt(num);
  for (ll i = 3; i <= sqrtNum; i += 2)
  {
    if (num % i == 0)
      return false;
  }
  return true;
}
//桁数
ll GetDigit(ll num)
{
  return log10(num) + 1;
}
//各桁の和
ll KSum(ll n)
{
  ll sum = 0;
  if (n < 0)
    return 0;
  while (n > 0)
  {
    sum += n % 10;
    n /= 10;
  }
  return sum;
}
//数値反転
bool KReve(ll n)
{
  int reverse = 0;
  int remaind;
  int tmp = n;
  while (tmp != 0)
  {
    remaind = tmp % 10;
    reverse = reverse * 10 + remaind;
    tmp /= 10;
  }
  if (reverse == n)
    return true;
  else
    return false;
}
//約数全列挙
vector<ll> enum_div(ll n)
{
  vector<ll> ret;
  for (ll i = 1; i * i <= n; ++i)
  {
    if (n % i == 0)
    {
      ret.push_back(i);
      if (i != 1 && i * i != n)
      {
        ret.push_back(n / i);
      }
    }
  }
  return ret;
}
//最大公約数
ll gcd(ll a, ll b)
{
  return b ? gcd(b, a % b) : a;
}
//複数個の最大公約数
ll ngcd(vector<ll> a)
{
  ll res;
  res = a[0];
  for (ll i = 1; i < a.size() && res != 1; i++)
  {
    res = gcd(a[i], res);
  }
  return res;
}
//最小公倍数
ll lcm(ll a, ll b)
{
  return a * b / gcd(a, b);
}
//複数個の最小公倍数
ll nlcm(vector<ll> numbers)
{
  ll res;
  res = numbers[0];
  for (ll i = 1; i < numbers.size(); i++)
  {
    res = lcm(res, numbers[i]);
  }
  return res;
}
//累乗
ll Pow(ll x, ll n)
{
  ll res = 1;
  rep(i, n) res = res * x;
  return res;
}
//累乗(xのn乗%mod)
ll mod_pow(ll x, ll n, ll mod = MAX)
{
  ll res = 1;
  while (n > 0)
  {
    if (n & 1)
      res = res * x % mod;
    x = x * x % mod;
    n >>= 1;
  }
  return res;
}
//階乗
ll factorial(ll n)
{
  if (n > 0)
    return n * factorial(n - 1);
  else
    return 1;
}
//順列 nPr
ll perm(ll a, ll b)
{
  return (factorial(a) / factorial(a - b));
}
//組み合わせ　nCr
ll comb(ll a, ll b)
{
  return (factorial(a) / (factorial(a - b) * factorial(b)));
}
//n ~ mの和
ll sigma(ll n, ll m)
{
  return ((n + m) * (m - n + 1) * 0.5);
}
//期待値
ld hope(ld a)
{
  return (sigma(1, a) / a);
}
//謎
template <class T>
inline bool chmax(T &a, T b)
{
  if (a < b)
  {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool chmin(T &a, T b)
{
  if (a > b)
  {
    a = b;
    return 1;
  }
  return 0;
}
/*
//幅優先探索
// 各座標に格納したい情報を構造体にする
// 今回はX座標,Y座標,深さ(距離)を記述している
struct Corr
{
  ll x;
  ll y;
  ll depth;
};
queue<Corr> q;
ll bfs(vector<vector<ll>> grid)
{
  // 既に探索の場所を1，探索していなかったら0を格納する配列
  vector<vector<ll>> ispassed(grid.size(), vector<ll>(grid[0].size(), false));
  // このような記述をしておくと，この後のfor文が綺麗にかける
  ll dx[8] = {1, 0, -1, 0};
  ll dy[8] = {0, 1, 0, -1};
  while (!q.empty())
  {
    Corr now = q.front();
    q.pop();
    //今いる座標は(x,y)=(now.x, now.y)で，深さ(距離)はnow.depthである  ここで，今いる座標がゴール(探索対象)なのか判定する
    for (ll i = 0; i < 4; i++)
    {
      ll nextx = now.x + dx[i];
      ll nexty = now.y + dy[i];

      // 次に探索する場所のX座標がはみ出した時
      if (nextx >= grid[0].size())
        continue;
      if (nextx < 0)
        continue;

      // 次に探索する場所のY座標がはみ出した時
      if (nexty >= grid.size())
        continue;
      if (nexty < 0)
        continue;

      // 次に探索する場所が既に探索済みの場合
      if (ispassed[nexty][nextx])
        continue;

      ispassed[nexty][nextx] = true;
      Corr next = {nextx, nexty, now.depth + 1};
      q.push(next);
    }
  }
}
*/
//謎
//セグメント木
class Monoid
{
public:
  // 単位元
  ll unit;

  Monoid()
  {
    // 単位元
    unit = 0;
  }

  // 演算関数
  ll calc(ll a, ll b)
  {
    return a + b;
  }
};

class SegmentTree
{
public:
  // セグメント木の葉の要素数
  ll n;

  // セグメント木
  vector<ll> tree;

  // モノイド
  Monoid mono;

  SegmentTree(vector<ll> &v)
  {
    n = 1 << (ll)ceil(log2(v.size()));
    tree = vector<ll>(n << 1);
    for (ll i = 0; i < v.size(); i++)
    {
      update(i, v[i]);
    }
    for (ll i = v.size(); i < n; i++)
    {
      update(i, mono.unit);
    }
  }

  // k番目の値(0-indexed)をxに変更
  void update(ll k, ll x)
  {
    k += n;
    tree[k] = x;
    for (k = k >> 1; k > 0; k >>= 1)
    {
      tree[k] = mono.calc(tree[k << 1 | 0], tree[k << 1 | 1]);
    }
  }

  // [l, r)の最小値(0-indexed)を求める．
  ll query(ll l, ll r)
  {
    ll res = mono.unit;
    l += n;
    r += n;
    while (l < r)
    {
      if (l & 1)
      {
        res = mono.calc(res, tree[l++]);
      }
      if (r & 1)
      {
        res = mono.calc(res, tree[--r]);
      }
      l >>= 1;
      r >>= 1;
    }
    return res;
  }
  ll operator[](ll k)
  {
    // st[i]で添字iの要素の値を返す
    if (k - n >= 0 || k < 0)
    {
      return -INF;
    }
    return tree[tree.size() - n + k];
  }

  void show()
  {
    int ret = 2;
    for (ll i = 1; i < 2 * n; i++)
    {
      cout << tree[i] << " ";
      if (i == ret - 1)
      {
        cout << endl;
        ret <<= 1;
      }
    }
    cout << endl;
  }
};
//点と線の最短距離
struct Point
{
  ld x;
  ld y;
};

struct LineSegment
{
  Point start;
  Point end;
};

/**
   @brief 線分と点の距離を計算する。
   @param line 線分
   @param point 点
   @return ユークリッド距離
 */
ld calc_dist(const LineSegment &line, const Point &point)
{
  ld x0 = point.x, y0 = point.y;
  ld x1 = line.start.x, y1 = line.start.y;
  ld x2 = line.end.x, y2 = line.end.y;

  ld a = x2 - x1;
  ld b = y2 - y1;
  ld a2 = a * a;
  ld b2 = b * b;
  ld r2 = a2 + b2;
  ld tt = -(a * (x1 - x0) + b * (y1 - y0));

  if (tt < 0)
    return sqrt((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));
  else if (tt > r2)
    return sqrt((x2 - x0) * (x2 - x0) + (y2 - y0) * (y2 - y0));

  ld f1 = a * (y1 - y0) - b * (x1 - x0);
  return sqrt((f1 * f1) / r2);
}
//文字を数字に
ll Moji(char a)
{
  return (a - 48);
}

//大文字->小文字(+32)

void Main()
{
  ll h, w; cin >> h >> w;
  if(h * w % 2 == 1) fin(h * w / 2 + 1)
  else fin(h * w / 2)
}

int main()
{
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed << setprecision(20);
  Main();
  return 0;
}
/*
//test時
g++ test.cpp -o a;./a
*/


#include <bits/stdc++.h>
using namespace std;
using lint = long;
using ll = long long;
#define rep(i,n) for(lint (i) = 0;(i) < (lint)(n);(i)++)
#define repInRange(i,start,end) for(lint (i) = (start);(i) < (end);++(i))
using lpair = pair<lint,lint>;
using Vecint = vector<lint>;
using Llist = list<lint>;

ll pow(ll k,ll l) {
	ll ret = 1;
	rep(i,l) {
		ret *= k;
	}
	return ret;
}

template <typename T>
T sum(vector<T> vec) {
	ll ret = 0;
	rep(i,vec.size()) {
		ret += vec.at(i);
	}
	return ret;
}

void Main() {
	ll h,w;
	cin >> h >> w;
	cout << h*w/2 + (h*w)%2 << '\n';
}

signed main() {
	cin.tie(nullptr);
	ios::sync_with_stdio(false);
	Main();
	return 0;
}


#include<cstdio>

long long n, m;

int main() {
  scanf("%lld %lld", &n, &m);
  if (n == 1 || m == 1) {
    printf("1\n");
  } else {
    printf("%lld\n", (n*m+1)/2);
  }
}


#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
#include <iostream>
#include <queue>
#include <stack>
#define lson rt<<1
#define rson rt<<1|1
using namespace std;
typedef long long ll;
typedef pair<int, int>  P;
typedef pair<int, P>  PP;
const int maxn=43+10;
char a[maxn],b[maxn],c[maxn];
bool xab[maxn],xba[maxn],xbc[maxn],xac[maxn],xcb[maxn];
int main()
{
    cin>>a>>b>>c;
    int lena=strlen(a),lenb=strlen(b),lenc=strlen(c);
    int len=max(max(strlen(a),strlen(b)),strlen(c));
    for(int i=-len;i<=len;i++)
    {
        int flag=0;
        for(int j=0;j<lena;j++)
        {
            if(0<=j+i&&j+i<lenb)
            {
                if(a[j]!='?'&&a[j]!=b[i+j]&&b[i+j]!='?')
                {
                    flag=1;
                    break;
                }
            }
        }
        if(flag==0){
            xab[i+len]=1;
        }
    }

    for(int i=-len;i<=len;i++)
    {
        int flag=0;
        for(int j=0;j<lenb;j++)
        {
            if(0<=j+i&&j+i<lenc)
            {
                if(b[j]!='?'&&b[j]!=c[i+j]&&c[i+j]!='?')
                {
                    flag=1;
                    break;
                }
            }
        }
        if(flag==0){
            xbc[i+len]=1;
        }
    }

    for(int i=-len;i<=len;i++)
    {
        int flag=0;
        for(int j=0;j<lena;j++)
        {
            if(0<=j+i&&j+i<lenc)
            {
                if(a[j]!='?'&&a[j]!=c[i+j]&&c[i+j]!='?')
                {
                    flag=1;
                    break;
                }
            }
        }
        if(flag==0)
            xac[i+len]=1;
    }

    int ans=1e9;
    for(int i=-len*2;i<=len*2;i++)
        for(int j=-len*2;j<=len*2;j++)
        {
            int l=0,r=lena;
            l=min(min(-i,-j),l);
            r=max(r,max(-i+lenb,-j+lenc));
            if(-len<=i&&i<=len&&xab[i+len]==0)
                continue;
            int p=j-i;
            if(-len<=p&&p<=len&&xbc[p+len]==0)
                continue;

            if(-len<=j&&j<=len&&xac[j+len]==0)
                continue;

            ans=min(r-l,ans);
            if(ans==4)
                cout<<i<<" "<<j<<endl;
        }
    cout<<ans;
}

Score : 500 points

Problem Statement

Snuke has a string s.
From this string, Anuke, Bnuke, and Cnuke obtained strings a, b, and c, respectively, as follows:

Choose a non-empty (contiguous) substring of s (possibly s itself). Then, replace some characters (possibly all or none) in it with ?s.

For example, if s is mississippi, we can choose the substring ssissip and replace its 1-st and 3-rd characters with ? to obtain ?s?ssip.

You are given the strings a, b, and c.
Find the minimum possible length of s.

Constraints

1 \leq |a|, |b|, |c| \leq 2000

a, b, and c consists of lowercase English letters and ?s.

Input

Input is given from Standard Input in the following format:

a
b
c

Output

Print the minimum possible length of s.

Sample Input 1

a?c
der
cod

Sample Output 1

7

For example, s could be atcoder.

Sample Input 2

atcoder
atcoder
???????

Sample Output 2

7

a, b, and c may not be distinct.


#include<iostream>
#include<vector>
using namespace std;
typedef long long li;
#define rep(i,n) for(int i=0;i<(n);i++)
#define df 0
template<class T> void print(const T& t){ cout << t << "\n"; }
template<class T, class... Ts> void print(const T& t, const Ts&... ts) { cout << t; if (sizeof...(ts)) cout << " "; print(ts...); }
// Container コンテナ型, map以外
template< template<class ...> class Ctn,class T>
std::ostream& operator<<(std::ostream& os,const Ctn<T>& v){
  auto itr=v.begin();
  while(itr!=v.end()){
    if(itr!=v.begin())cout << " ";
    cout << *(itr++);
  }
  return os;
}

void dfs(vector<vector<int>>& adj,vector<vector<int>>& col,
         int p=-1,int a=0){
  int n=adj.size();
  static vector<int> seen(n,0);
  static int c=0;
  seen[a]=1;
  col[c].push_back(a);
  c^=1;
  for(int x:adj[a]){
    if(x==p) continue;
    dfs(adj,col,a,x);
  }
  c^=1;
}

void balance(vector<int>& p,vector<vector<int>> col){
  int n=p.size();
  int a=0,b=1;
  if(col[0].size()<col[1].size()){ a=1;b=0; }

  rep(i,n){
    if(i%3==0){
      p[*col[a].rbegin()]=i+1;
      col[a].pop_back();
    }else if(i%3==1){
      p[*col[b].rbegin()]=i+1;
      col[b].pop_back();
    }else{
      int c=(col[0].size()<=col[1].size());
      p[*col[c].rbegin()]=i+1;
      col[c].pop_back();
    }
  }
}

void umbalance(vector<int>& p,vector<vector<int>> col){
  int n=p.size();
  int a=0,b=1;
  if(col[0].size()<col[1].size()){ a=1;b=0; }
  int c=3;
  while(c<=n){
    p[*col[b].rbegin()]=c;
    col[b].pop_back();
    c+=3;
    if(col[b].size()==0) b=a;
  }
  c=1;
  for(int x: col[a]){
    p[x]=c;
    c+=c%3;
  }
}

int main(){
  int n; cin >>n;
  vector<vector<int>> adj(n);
  rep(i,n-1){
    int a,b; cin >>a >>b; a--; b--;
    adj[a].push_back(b);
    adj[b].push_back(a);
  }
  vector<vector<int>> col(2);
  dfs(adj,col);

  vector<int> p(n);
  int a=0,b=1;
  if(col[0].size()<col[1].size()){ a=1;b=0; }
  if(col[a].size()<col[b].size()*2){
    balance(p,col);
  }else{
    umbalance(p,col);
  }
  print(p);
}

Score : 600 points

Problem Statement

We have a tree with N vertices. The vertices are numbered 1 to N, and the i-th edge connects Vertex a_i and Vertex b_i.

Takahashi loves the number 3. He is seeking a permutation p_1, p_2, \ldots , p_N of integers from 1 to N satisfying the following condition:

For every pair of vertices (i, j), if the distance between Vertex i and Vertex j is 3, the sum or product of p_i and p_j is a multiple of 3.

Here the distance between Vertex i and Vertex j is the number of edges contained in the shortest path from Vertex i to Vertex j.

Help Takahashi by finding a permutation that satisfies the condition.

Constraints

2\leq N\leq 2\times 10^5

1\leq a_i, b_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N
a_1 b_1
a_2 b_2
\vdots
a_{N-1} b_{N-1}

Output

If no permutation satisfies the condition, print -1.

Otherwise, print a permutation satisfying the condition, with space in between.
If there are multiple solutions, you can print any of them.

Sample Input 1

5
1 2
1 3
3 4
3 5

Sample Output 1

1 2 5 4 3

The distance between two vertices is 3 for the two pairs (2, 4) and (2, 5).

p_2 + p_4 = 6

p_2\times p_5 = 6

Thus, this permutation satisfies the condition.


#include <bits/stdc++.h>
#define _overload3(_1, _2, _3, name, ...) name
#define _rep(i, n) repi(i, 0, n)
#define repi(i, a, b) for (ll i = (ll)(a); i < (ll)(b); ++i)
#define rep(...) _overload3(__VA_ARGS__, repi, _rep, )(__VA_ARGS__)
#define ll long long
#define lld long double
#define ALL(x) x.begin(), x.end()
using namespace std;
const ll INF = 1ll << 60;
map<int, vector<int>> g;
map<int, int> color;
int red = 0;
int blue = 0;

void dfs(int cur, int par, int col)
{
    color[cur] = col;
    if (col == 0)
        red++;
    else
        blue++;
    for (auto x : g[cur])
    {
        if (x != par)
        {
            dfs(x, cur, (col + 1) % 2);
        }
    }
}

int main()
{
    int n;
    cin >> n;
    rep(i, n - 1)
    {
        int a, b;
        cin >> a >> b;
        g[a].push_back(b);
        g[b].push_back(a);
    }
    dfs(1, 0, 0);
    deque<int> q[3];
    rep(i, 1, n + 1) q[i % 3].push_back(i);
    map<int, int> ans;
    //0:red 1:blue
    if (red <= n / 3)
    {
        rep(i, 1, n + 1)
        {
            if (color[i] == 0)
            {
                ans[i] = q[0].front();
                q[0].pop_front();
            }
            else
            {
                for (int j = 2; j >= 0; j--)
                {
                    if (!q[j].empty())
                    {
                        ans[i] = q[j].front();
                        q[i].pop_front();
                    }
                }
            }
        }
    }
    else if (blue <= n / 3)
    {
        rep(i, 1, n + 1)
        {
            if (color[i] == 1)
            {
                ans[i] = q[0].front();
                q[0].pop_front();
            }
            else
            {
                for (int j = 2; j >= 0; j--)
                {
                    if (!q[j].empty())
                    {
                        ans[i] = q[j].front();
                        q[i].pop_front();
                    }
                }
            }
        }
    }
    else
    {
        rep(i, 1, n + 1)
        {
            if (color[i] == 0)
            {
                if (!q[1].empty())
                {
                    ans[i] = q[1].front();
                    q[1].pop_front();
                }
                else
                {
                    ans[i] = q[0].front();
                    q[0].pop_front();
                }
            }
            else
            {
                if (!q[2].empty())
                {
                    ans[i] = q[2].front();
                    q[2].pop_front();
                }
                else
                {
                    ans[i] = q[0].front();
                    q[0].pop_front();
                }
            }
        }
    }
    rep(i, 1, n + 1)
    {
        cout << ans[i] << " ";
    }
    cout << endl;
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define FOR(i, a, b) for(int i=(a);i<(b);++i)
#define rep(i, n) FOR(i, 0, n)
#define whole(x) (x).begin(),(x).end()
#define UNIQUE(v) v.erase(unique(v.begin(), v.end()), v.end())
using ll = long long;
using P = pair<int, int>;
const int mod = 1000000007;

vector<int> to[200005];
//int root[200005];
int depth[200005];

void dfs(int v, int p=-1) {
    if (p==-1) depth[v] = 0;
    else {
        depth[v] = depth[p]+1;
    }
    for(int e: to[v]) {
        if(e==p) continue;
        dfs(e, v);
    }

}

int main(){
    int n;
    cin >> n;
    vector<int> p(n);
    rep(i, n-1) {
        int a, b;
        cin >> a >> b;
        a--; b--;
        if (a>b) swap(a, b);
        to[a].push_back(b);
        to[b].push_back(a);
    }
    dfs(0, -1);
    int odd = 0;
    int even = 0;
    rep(i, n) {
        if (depth[i]%2) odd++;
        else even++;
    }
    int mod3[3];
    rep(i, 3) {
        if (n%3==0) {
            mod3[0] = n/3;
            mod3[1] = n/3;
            mod3[2] = n/3;
        }
        else if (n%3==1) {
            mod3[0] = n/3;
            mod3[1] = n/3+1;
            mod3[2] = n/3+1;
        }
        else {
            mod3[0] = n/3;
            mod3[1] = n/3+1;
            mod3[2] = n/3+1;
        }
    }
    if (max(odd, even)>(mod3[0]+mod3[1])) {
        cout << "-1" << endl;
        return 0;
    }

    vector<int> ans(n);
    queue<int> res[3];
    rep(i, n) {
        int v = (i+1)%3;
        res[v].push(i+1);
    }
    if (even>odd) {
        rep(i, n) {
            depth[i]++;
        }
    }
    rep(i, n) {
        if(depth[i]%2) {
            if (!res[1].empty()) {
                ans[i] = res[1].front();
                res[1].pop();
            }
            else {
                ans[i] = res[0].front();
                res[0].pop();
            }
        }
        else {
            if (!res[2].empty()) {
                ans[i] = res[2].front();
                res[2].pop();
            }
            else {
                ans[i] = res[0].front();
                res[0].pop();
            }
        }
        cout << ans[i] << " ";
    }
    cout << endl;

    return 0;
}


#include <bits/stdc++.h>
using namespace std;

template<typename T>
void out(T x) { cout << x << endl; exit(0); }
#define watch(x) cout << (#x) << " is " << (x) << endl

using ll = long long;

const ll mod = 1e9+7;
const int maxn = 1e3 + 5;
const ll inf = 1e18;

struct store {
    ll a, b;
    void read() {
	cin>>a>>b;
    }
    bool operator<(const store&o ) const {
	//return b/a < o.b/o.a;
	return (1+b)*o.a < (1+o.b)*a;
    }
};

int n;
ll T;

void relax(ll &x, ll y) {
    x = min(x, y);
}

int main() {
    ios_base::sync_with_stdio(false); cin.tie(0);  cout.tie(0);

    cin>>n>>T;
    vector<store> v;
    vector<ll> B;
    for (int i=0; i<n; i++) {
	store s;
	s.read();
	if (s.a==0) {
	    B.push_back(s.b);
	} else {
	    v.push_back(s);
	}
    }

    sort(v.begin(), v.end());

    const int N = 50; // > 1e9
    // a(aT+b+1)+b -> a^i -> exponential time increase

    vector<ll> dp(N+1, inf);
    dp[0] = 0;

    for (int i=0; i<(int)v.size(); i++) {
	for (int j=N; j>=0; j--) {
	    if (dp[j] < T) {
		relax(dp[j+1], dp[j] + 1 + ((dp[j]+1)*v[i].a + v[i].b));
	    }
	}
    }

    sort(B.begin(), B.end());
    vector<ll> cost;
    cost.push_back(0);
    for (int i=1; i<(int)B.size(); i++) {
	B[i] += B[i-1];
    }
    for (int i=0; i<(int)B.size(); i++) {
	cost.push_back((i+1) + B[i]);
    }

    int hi = 0;
    for (int i=0; i<=N; i++) {
	if (dp[i] <= T) {
	    ll leftover = T-dp[i];
	    auto iter = std::prev(upper_bound(cost.begin(), cost.end(), leftover));
	    int take = i + (iter-cost.begin());
	    //watch(iter-cost.begin());
	    hi = max(hi, take);
	}
    }

    cout<<hi<<endl;
    return 0;
}

Score : 800 points

Problem Statement

There are N stores called Store 1, Store 2, \cdots, Store N. Takahashi, who is at his house at time 0, is planning to visit some of these stores.

It takes Takahashi one unit of time to travel from his house to one of the stores, or between any two stores.

If Takahashi reaches Store i at time t, he can do shopping there after standing in a queue for a_i \times t + b_i units of time. (We assume that it takes no time other than waiting.)

All the stores close at time T + 0.5. If Takahashi is standing in a queue for some store then, he cannot do shopping there.

Takahashi does not do shopping more than once in the same store.

Find the maximum number of times he can do shopping before time T + 0.5.

Constraints

All values in input are integers.

1 \leq N \leq 2 \times 10^5

0 \leq a_i \leq 10^9

0 \leq b_i \leq 10^9

0 \leq T \leq 10^9

Input

Input is given from Standard Input in the following format:

N T
a_1 b_1
a_2 b_2
\vdots
a_N b_N

Output

Print the answer.

Sample Input 1

3 7
2 0
3 2
0 3

Sample Output 1

2

Here is one possible way to visit stores:

From time 0 to time 1: in 1 unit of time, he travels from his house to Store 1.

From time 1 to time 3: for 2 units of time, he stands in a queue for Store 1 to do shopping.

From time 3 to time 4: in 1 unit of time, he travels from Store 1 to Store 3.

From time 4 to time 7: for 3 units of time, he stands in a queue for Store 3 to do shopping.

In this way, he can do shopping twice before time 7.5.

Sample Input 2

1 3
0 3

Sample Output 2

0

Sample Input 3

5 21600
2 14
3 22
1 3
1 10
1 9

Sample Output 3

5

Sample Input 4

7 57
0 25
3 10
2 4
5 15
3 22
2 14
1 15

Sample Output 4

3


#include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
#define sz(x) int(x.size())
using namespace std;

typedef long long ll;
// const int INF = 1e8;
const ll INF = 1LL << 60;
typedef pair<int, int> P;

ll N, M;

int main() {
    cin >> N >> M;
    ll n = pow(2, N) - 1;
    ll m = pow(2, M) - 1;

    if (n == 1) {
        rep(i, m) {
            cout << 1;
        }
        cout << endl;
        return 0;
    } else if (m == 1) {
        rep(i, n) {
            cout << 1 << endl;
        }
        return 0;
    }

    rep(i, n) {
        rep(j, m) {
            if (i == 0 && j == 0) cout << 0;
            else cout << 1;
        }
        cout << endl;
    }
}

Score : 900 points

Problem Statement

We have a grid with (2^N - 1) rows and (2^M-1) columns.
You are asked to write 0 or 1 in each of these squares.
Let a_{i,j} be the number written in the square at the i-th row from the top and the j-th column from the left.

For a quadruple of integers (i_1, i_2, j_1, j_2) such that 1\leq i_1 \leq i_2\leq 2^N-1, 1\leq j_1 \leq j_2\leq 2^M-1, let
S(i_1, i_2, j_1, j_2) = \displaystyle \sum_{r=i_1}^{i_2}\sum_{c=j_1}^{j_2}a_{r,c}.
Then, let the oddness of the grid be the number of quadruples (i_1, i_2, j_1, j_2) such that S(i_1, i_2, j_1, j_2) is odd.

Find a way to fill in the grid that maximizes its oddness.

Constraints

N and M are integers between 1 and 10 (inclusive).

Input

Input is given from Standard Input in the following format:

N M

Output

Print numbers to write in the grid so that its oddness is maximized, in the following format:

a_{1,1}a_{1,2}\cdots a_{1,2^M-1}
a_{2,1}a_{2,2}\cdots a_{2,2^M-1}
\vdots
a_{2^N-1,1}a_{2^N-1,2}\cdots a_{2^N-1,2^M-1}

If there are multiple solutions, you can print any of them.

Sample Input 1

1 2

Sample Output 1

111

For this grid, S(1, 1, 1, 1), S(1, 1, 2, 2), S(1, 1, 3, 3), and S(1, 1, 1, 3) are odd, so it has the oddness of 4.

We cannot make the oddness 5 or higher, so this is one of the ways that maximize the oddness.