Kayaks CodeChef Solution

Problem -Kayaks CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Kayaks CodeChef Solution in C++14

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip> 
#include <math.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <functional>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <bitset>
#include <complex>

using namespace std;

typedef long long LL;
typedef pair<LL, LL> PL;
typedef vector<LL> VL;
typedef vector<PL> VPL;
typedef vector<VL> VVL;

typedef pair<int, int> PI;
typedef vector<int> VI;
typedef vector<PI> VPI;
typedef vector<vector<int>> VVI;
typedef vector<vector<PI>> VVPI;

typedef long double LD;
typedef pair<LD, LD> PLDLD;

typedef complex<double> CD;
typedef vector<CD> VCD;

typedef vector<string> VS;

#define MP make_pair
#define PB push_back
#define F first
#define S second
#define LB lower_bound
#define UB upper_bound

#define SZ(x) ((int)x.size())
#define LEN(x) ((int)x.length())
#define ALL(x) begin(x), end(x)
#define RSZ resize
#define ASS assign
#define REV(x) reverse(x.begin(), x.end());



#define FOR(i, a, b) for (int i = (a); i < (b); i++)
#define F0R(i, a) for (int i = 0; i < (a); i++)
#define FORd(i,a,b) for (int i = (b)-1; i >= (a); i--)
#define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--)
#define trav(a, x) for (auto& a : x)


const LL INF = 1E18;
const int MAXX = 300005;
const LD PAI = 4 * atan((LD)1);

template <typename T>
class fenwick_tree {
public:
    vector<T> fenw;
    int n;

    fenwick_tree(int _n) : n(_n) {
        fenw.resize(n);
    }

    void update(int x, T v) {
        while (x < n) {
            fenw[x] += v;
            x |= (x + 1);
            //x += (x & (-x));
        }
    }

    T query(int x) {
        T v{};
        while (x >= 0) {
            v += fenw[x];
            x = (x & (x + 1)) - 1;
        }
        return v;
    }

    T query_full(int a, int b) {		// range query
        return query(b) - ((a <= 1) ? 0 : query(a - 1));
    }
};

template <typename T>
vector<T> serialize(vector<T> a, int startvalue = 0) {
    int n = a.size(), i, j, k, ct;
    vector<T> ans(n);
    map<T, T> id;
    for (auto p : a) id[p] = 0;
    ct = startvalue;
    for (auto p : id) id[p.first] = ct++;
    for (i = 0; i < n; i++) ans[i] = id[a[i]];
    return ans;
}

template <typename T>
class segment_tree {
    vector<T> t;
    T VERYBIG;
    bool ISMAXRANGE;
    int size;
public:
    segment_tree(int n, bool range_max = true) {
        if (is_same<T, int>::value) VERYBIG = (1 << 30);
        else if (is_same<T, LL>::value) VERYBIG = (1LL << 60);
        //else if (is_same<T, PII>::value) VERYBIG = PII({ 1E9, 1E9 });
        //else if (is_same<T, PLL>::value) VERYBIG = { 1LL << 60, 1LL << 60 };

        ISMAXRANGE = range_max;

        if (ISMAXRANGE) t.assign(4 * n + 1, 0);
        else t.assign(4 * n + 1, VERYBIG);
        size = n;
    }

    void initialize_array(vector<T>& v) {
        initialize_with_array(1, 0, size - 1, v);
    }

    void initialize_with_array(int startpos, int l, int r, vector<T>& v) {
        if (l == r) {
            t[startpos] = v[l];
        }
        else {
            int m = (l + r) / 2;
            initialize_with_array(2 * startpos, l, m, v);
            initialize_with_array(2 * startpos + 1, m + 1, r, v);

            if (ISMAXRANGE == 1) t[startpos] = max(t[startpos * 2], t[startpos * 2 + 1]);
            else  t[startpos] = min(t[startpos * 2], t[startpos * 2 + 1]);
        }
    }

    void update(int index, T val) { // insert val into location index
        update_full(1, 0, size - 1, index, val);
    }

    void update_full(int startpos, int l, int r, int index, T val) {
        if (l == r) {
            t[startpos] = val;
        }
        else {
            int m = (l + r) / 2;
            if (index <= m) update_full(2 * startpos, l, m, index, val);
            else update_full(2 * startpos + 1, m + 1, r, index, val);

            if (ISMAXRANGE) t[startpos] = max(t[startpos * 2], t[startpos * 2 + 1]);
            else t[startpos] = min(t[startpos * 2], t[startpos * 2 + 1]);
        }
    }

    T query(int l, int r) {  // get range min/max between l and r
        if (l > r) {
            if (ISMAXRANGE) return 0;
            else return VERYBIG;
        }
        return query_full(1, 0, size - 1, l, r);
    }

    T query_full(int startpos, int left, int right, int l, int r) {	 // left/right = current range, l/r = intended query range
        if ((left >= l) && (right <= r)) return t[startpos];
        int m = (left + right) / 2;
        T ans;
        if (ISMAXRANGE) ans = -VERYBIG;
        else ans = VERYBIG;
        if (m >= l) {
            if (ISMAXRANGE) ans = max(ans, query_full(startpos * 2, left, m, l, r));
            else ans = min(ans, query_full(startpos * 2, left, m, l, r));
        }
        if (m + 1 <= r) {
            if (ISMAXRANGE) ans = max(ans, query_full(startpos * 2 + 1, m + 1, right, l, r));
            else ans = min(ans, query_full(startpos * 2 + 1, m + 1, right, l, r));
        }
        return ans;
    }
};

//#define MOD 1000000007
int MOD = 1, root = 2; // 998244353

template<class T> T invGeneral(T a, T b) {
    a %= b; if (a == 0) return b == 1 ? 0 : -1;
    T x = invGeneral(b, a);
    return x == -1 ? -1 : ((1 - (LL)b * x) / a + b) % b;
}

template<class T> struct modular {
    T val;
    explicit operator T() const { return val; }
    modular() { val = 0; }
    modular(const LL& v) {
        val = (-MOD <= v && v <= MOD) ? v : v % MOD;
        if (val < 0) val += MOD;
    }

    friend ostream& operator<<(ostream& os, const modular& a) { return os << a.val; }
    friend bool operator==(const modular& a, const modular& b) { return a.val == b.val; }
    friend bool operator!=(const modular& a, const modular& b) { return !(a == b); }
    friend bool operator<(const modular& a, const modular& b) { return a.val < b.val; }

    modular operator-() const { return modular(-val); }
    modular& operator+=(const modular& m) { if ((val += m.val) >= MOD) val -= MOD; return *this; }
    modular& operator-=(const modular& m) { if ((val -= m.val) < 0) val += MOD; return *this; }
    modular& operator*=(const modular& m) { val = (LL)val * m.val % MOD; return *this; }
    friend modular pow(modular a, LL p) {
        modular ans = 1; for (; p; p /= 2, a *= a) if (p & 1) ans *= a;
        return ans;
    }
    friend modular inv(const modular& a) {
        auto i = invGeneral(a.val, MOD); assert(i != -1);
        return i;
    } // equivalent to return exp(b,MOD-2) if MOD is prime
    modular& operator/=(const modular& m) { return (*this) *= inv(m); }

    friend modular operator+(modular a, const modular& b) { return a += b; }
    friend modular operator-(modular a, const modular& b) { return a -= b; }
    friend modular operator*(modular a, const modular& b) { return a *= b; }

    friend modular operator/(modular a, const modular& b) { return a /= b; }
};

typedef modular<int> mi;
typedef pair<mi, mi> pmi;
typedef vector<mi> vmi;
typedef vector<pmi> vpmi;

//mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

namespace vecOp {
    template<class T> vector<T> rev(vector<T> v) { reverse(ALL(v)); return v; }
    template<class T> vector<T> shift(vector<T> v, int x) { v.insert(v.begin(), x, 0); return v; }

    template<class T> vector<T>& operator+=(vector<T>& l, const vector<T>& r) {
        l.rSZ(max(SZ(l), SZ(r))); F0R(i, SZ(r)) l[i] += r[i]; return l;
    }
    template<class T> vector<T>& operator-=(vector<T>& l, const vector<T>& r) {
        l.rSZ(max(SZ(l), SZ(r))); F0R(i, SZ(r)) l[i] -= r[i]; return l;
    }
    template<class T> vector<T>& operator*=(vector<T>& l, const T& r) { trav(t, l) t *= r; return l; }
    template<class T> vector<T>& operator/=(vector<T>& l, const T& r) { trav(t, l) t /= r; return l; }

    template<class T> vector<T> operator+(vector<T> l, const vector<T>& r) { return l += r; }
    template<class T> vector<T> operator-(vector<T> l, const vector<T>& r) { return l -= r; }
    template<class T> vector<T> operator*(vector<T> l, const T& r) { return l *= r; }
    template<class T> vector<T> operator*(const T& r, const vector<T>& l) { return l * r; }
    template<class T> vector<T> operator/(vector<T> l, const T& r) { return l /= r; }

    template<class T> vector<T> operator*(const vector<T>& l, const vector<T>& r) {
        if (min(SZ(l), SZ(r)) == 0) return {};
        vector<T> x(SZ(l) + SZ(r) - 1); F0R(i, SZ(l)) F0R(j, SZ(r)) x[i + j] += l[i] * r[j];
        return x;
    }
    template<class T> vector<T>& operator*=(vector<T>& l, const vector<T>& r) { return l = l * r; }

    template<class T> vector<T> rem(vector<T> a, vector<T> b) {
        while (SZ(b) && b.back() == 0) b.pop_back();
        assert(SZ(b)); b /= b.back();
        while (SZ(a) >= SZ(b)) {
            a -= a.back() * shift(b, SZ(a) - SZ(b));
            while (SZ(a) && a.back() == 0) a.pop_back();
        }
        return a;
    }
    template<class T> vector<T> interpolate(vector<pair<T, T>> v) {
        vector<T> ret;
        F0R(i, SZ(v)) {
            vector<T> prod = { 1 };
            T todiv = 1;
            F0R(j, SZ(v)) if (i != j) {
                todiv *= v[i].f - v[j].f;
                vector<T> tmp = { -v[j].f,1 }; prod *= tmp;
            }
            ret += prod * (v[i].s / todiv);
        }
        return ret;
    }
}

using namespace vecOp;

class factorial {
public:
    LL MAXX, MOD;
    VL f, ff;

    factorial(LL maxx = 200010, LL mod = 998244353) {
        MAXX = maxx;
        MOD = mod;

        f.RSZ(MAXX);
        ff.RSZ(MAXX);

        f[0] = 1;
        for (int i = 1; i < MAXX; i++) f[i] = (f[i - 1] * i) % MOD;
        for (int i = 0; i < MAXX; i++) ff[i] = mul_inv(f[i], MOD);
    }

    long long mul_inv(long long a, long long b)
    {
        long long b0 = b, t, q;
        long long x0 = 0, x1 = 1;
        if (b == 1) return 1;
        while (a > 1) {
            q = a / b;
            t = b, b = a % b, a = t;
            t = x0, x0 = x1 - q * x0, x1 = t;
        }
        if (x1 < 0) x1 += b0;
        return x1;
    }

    long long division(long long a, long long b) {		// (a / b) mod p = ((a mod p) * (b^(-1) mod p)) mod p
        long long ans, inv;
        inv = mul_inv(b, MOD);
        ans = ((a % MOD) * inv) % MOD;
        return ans;
    }

    LL calcc(LL n, LL a) {
        if (n == a) return 1;
        if (n == 0) return 0;
        if (n < a) return 0;
        LL ans = (f[n] * ff[a]) % MOD;
        ans = (ans * ff[n - a]) % MOD;
        return ans;
    }

    LL calcp(LL n, LL a) {
        LL ans = (f[n] * ff[n - a]) % MOD;
        return ans;
    }

    LL exp(LL base, LL n) {
        base %= MOD;
        LL ans = 1, x = base, MAXLEVEL = 60, i;

        for (i = 0; i < MAXLEVEL; i++) {
            if ((1LL << i) > n) break;
            if ((1LL << i) & n) ans = (ans * x) % MOD;
            x = (x * x) % MOD;
        }
        return ans;
    }
};

#ifdef _MSC_VER 
//#include <intrin.h>
#endif

namespace FFT {
#ifdef _MSC_VER 
    int size(int s) {
        if (s == 0) return 0;
        unsigned long index;
        _BitScanReverse(&index, s);
        return index + 1;
    }
#else
    constexpr int size(int s) { return s > 1 ? 32 - __builtin_clz(s - 1) : 0; }
#endif

    template<class T> bool small(const vector<T>& a, const vector<T>& b) {
        return (LL)SZ(a) * SZ(b) <= 500000;
    }

    void genRoots(vmi& roots) { // primitive n-th roots of unity
        int n = SZ(roots); mi r = pow(mi(root), (MOD - 1) / n);
        roots[0] = 1; FOR(i, 1, n) roots[i] = roots[i - 1] * r;
    }
    void genRoots(VCD& roots) { // change cd to complex<double> instead?
        int n = SZ(roots); LD ang = 2 * PAI / n;
        F0R(i, n) roots[i] = CD(cos(ang * i), sin(ang * i)); // is there a way to do this more quickly?
    }

    template<class T> void fft(vector<T>& a, vector<T>& roots) {
        int n = SZ(a);
        for (int i = 1, j = 0; i < n; i++) { // sort by reverse bit representation
            int bit = n >> 1;
            for (; j & bit; bit >>= 1) j ^= bit;
            j ^= bit; if (i < j) swap(a[i], a[j]);
        }
        for (int len = 2; len <= n; len <<= 1)
            for (int i = 0; i < n; i += len)
                F0R(j, len / 2) {
                auto u = a[i + j], v = a[i + j + len / 2] * roots[n / len * j];
                a[i + j] = u + v, a[i + j + len / 2] = u - v;
            }
    }

    template<class T> vector<T> conv(vector<T> a, vector<T> b) {
        //if (small(a, b)) return a * b;
        int s = SZ(a) + SZ(b) - 1, n = 1 << size(s);
        vector<T> roots(n); genRoots(roots);

        a.RSZ(n), fft(a, roots); b.RSZ(n), fft(b, roots);
        F0R(i, n) a[i] *= b[i];
        reverse(begin(roots) + 1, end(roots)); fft(a, roots); // inverse FFT

        T in = T(1) / T(n); trav(x, a) x *= in;
        a.RSZ(s); return a;
    }

    VL conv(const VL& a, const VL& b) {
        //if (small(a, b)) return a * b;
        VCD X = conv(VCD(ALL(a)), VCD(ALL(b)));
        VL x(SZ(X)); F0R(i, SZ(X)) x[i] = round(X[i].real());
        return x;
    } // ~0.55s when SZ(a)=SZ(b)=1<<19

    VL conv(const VL& a, const VL& b, LL mod) { // http://codeforces.com/contest/960/submission/37085144
        //if (small(a, b)) return a * b;
        int s = SZ(a) + SZ(b) - 1, n = 1 << size(s);

        VCD v1(n), v2(n), r1(n), r2(n);
        F0R(i, SZ(a)) v1[i] = CD(a[i] >> 15, a[i] & 32767); // v1(x)=a0(x)+i*a1(x)
        F0R(i, SZ(b)) v2[i] = CD(b[i] >> 15, b[i] & 32767); // v2(x)=b0(x)+i*b1(x)

        VCD roots(n); genRoots(roots);
        fft(v1, roots), fft(v2, roots);
        F0R(i, n) {
            int j = (i ? (n - i) : i);
            CD ans1 = (v1[i] + conj(v1[j])) * CD(0.5, 0); // a0(x)
            CD ans2 = (v1[i] - conj(v1[j])) * CD(0, -0.5); // a1(x)
            CD ans3 = (v2[i] + conj(v2[j])) * CD(0.5, 0); // b0(x)
            CD ans4 = (v2[i] - conj(v2[j])) * CD(0, -0.5); // b1(x)
            r1[i] = (ans1 * ans3) + (ans1 * ans4) * CD(0, 1); // a0(x)*v2(x)
            r2[i] = (ans2 * ans3) + (ans2 * ans4) * CD(0, 1); // a1(x)*v2(x)
        }
        reverse(begin(roots) + 1, end(roots));
        fft(r1, roots), fft(r2, roots); F0R(i, n) r1[i] /= n, r2[i] /= n;

        VL ret(n);
        F0R(i, n) {
            LL av = (LL)round(r1[i].real()); // a0*b0
            LL bv = (LL)round(r1[i].imag()) + (LL)round(r2[i].real()); // a0*b1+a1*b0
            LL cv = (LL)round(r2[i].imag()); // a1*b1
            av %= mod, bv %= mod, cv %= mod;
            ret[i] = (av << 30) + (bv << 15) + cv;
            ret[i] = (ret[i] % mod + mod) % mod;
        }
        ret.resize(s);
        return ret;
    } // ~0.8s when SZ(a)=SZ(b)=1<<19
}
using namespace FFT;

long long gcd(long long a, long long b)
{
    while (b != 0) {
        long long t = b;
        b = a % b;
        a = t;
    }
    return a;
}



class tree {		// implementation of recurvie programming
    int ct;
public:
    int nn, root;				// # of nodes, id of root
    vector<int> parent;			// parent of each node; -1 if unassigned
    vector<int> depth;			// depth of each node
    vector<int> sz;				// subtree size of each node 
    vector<vector<int>> adj;	// adjacency list from each node
    vector<vector<int>> sons;	// sons list from each node

    // for cartesian_decomposition
    vector<int> in, out;		// starting and ending position of a subtree
    vector<int> pos;			// inorder of DFS

    // for LCA sparse table
    vector<vector<int>> pred;
    int MAXLEVEL;

    tree(int n) {
        nn = n;
        adj.clear();
        adj.resize(n);
    }

    void add_path(int a, int b) {
        adj[a].push_back(b);
        adj[b].push_back(a);
    }

    void add_directed_path(int a, int b) {
        adj[a].push_back(b);
    }

    void dfs_set_root(int id, bool cartesian_decomposition = false) {	// internal
        if (cartesian_decomposition) {
            in[id] = ct;
            pos[ct] = id;
            ct++;
        }

        sz[id]++;

        for (auto p : adj[id]) {
            if (parent[p] == -1) {
                parent[p] = id;
                depth[p] = depth[id] + 1;
                dfs_set_root(p, cartesian_decomposition);
                sz[id] += sz[p];

                sons[id].push_back(p);
            }
        }

        if (cartesian_decomposition) out[id] = ct - 1;
    }

    void set_root(int id, bool cartesian_decomposition = true) {		// set root of the tree and calculate necessary info
        if (cartesian_decomposition) {
            in.resize(nn);
            out.resize(nn);
            pos.resize(nn);
            ct = 0;
        }

        parent.assign(nn, -1);
        depth.assign(nn, -1);
        sz.assign(nn, 0);
        sons.clear();
        sons.resize(nn);

        // dfs_set_root(id, cartesian_decomposition);


        // set root using stack
        stack<pair<int, int>> st;		// id, # of sons processes
        st.push({ id, 0 });
        parent[id] = 0;
        depth[id] = 0;

        int ct = 0;

        while (!st.empty()) {
            int id = st.top().first, x = st.top().second;

            if (x == 0) {
                in[id] = ct;
                pos[ct] = id;
                sz[id] = 1;
                ct++;
            }

            if (x >= adj[id].size()) {
                out[id] = ct - 1;
                if (parent[id] != -1) {
                    sz[parent[id]] += sz[id];
                }
                st.pop();
            }
            else {

                st.top().second++;

                int p = adj[id][x];
                if (parent[p] == -1) {
                    parent[p] = id;
                    depth[p] = depth[id] + 1;
                    sons[id].push_back(p);
                    st.push({ p, 0 });
                }
            }
        }

        int i = 0;
    }

    void eulerian_tour_dfs(int root, vector<int>& ans) {
        ans.push_back(root);
        for (auto p : sons[root]) {
            eulerian_tour_dfs(p, ans);
            ans.push_back(root);
        }
    }

    vector<int> eulerian_tour(int root) {
        vector<int> ans;

        eulerian_tour_dfs(root, ans);

        return ans;
    }


    void prep_LCA() {		// prepare the sparse table for LCA calculation
        MAXLEVEL = 1;
        while ((1 << MAXLEVEL) < nn) MAXLEVEL++;
        MAXLEVEL++;

        pred.assign(MAXLEVEL, vector<int>(nn, 0));
        pred[0] = parent;

        int i, j, k;
        for (i = 1; i < MAXLEVEL; i++) {
            for (j = 0; j < nn; j++) {
                if (pred[i - 1][j] != -1) pred[i][j] = pred[i - 1][pred[i - 1][j]];
            }
        }
    }

    int get_p_ancestor(int a, int p) {		// get p-ancestor of node a;  need to call set_root() and prep_LCA() first
        int i;
        for (i = MAXLEVEL - 1; (i >= 0) && (p > 0) && (a != -1); i--) {
            if ((1 << i) & p) {
                p -= (1 << i);
                a = pred[i][a];
            }
        }
        return a;
    }

    int LCA(int a, int b) {		// get the LCA of a and b, need to call set_root() and prep_LCA() first
        int da = depth[a], db = depth[b];

        if (da > db) {
            swap(da, db);
            swap(a, b);
        }

        int i, j, k;
        for (i = MAXLEVEL - 1; i >= 0; i--) {
            if (db - (1 << i) >= da) {
                db -= (1 << i);
                b = pred[i][b];
            }
        }

        if (a == b) return a;

        for (i = MAXLEVEL - 1; i >= 0; i--) {
            if (pred[i][a] != pred[i][b]) {
                a = pred[i][a];
                b = pred[i][b];
            }
        }

        return parent[a];
    }

    int get_distance(int a, int b) {	// get distance between a and b, need to call set_root() and prep_LCA() first
        int c = LCA(a, b);
        int ans = depth[a] + depth[b] - 2 * depth[c];
        return ans;
    }

    int get_diameter() {
        int a, b, c, i, j, k, id, INF = nn + 100, ans;
        vector<int> dist(nn), last(nn);
        queue<int> q;

        if (nn == 1) return 0;

        // first pass, start with 1 -- any node
        a = 1;
        dist.assign(nn, INF);
        dist[a] = 0;
        q.push(a);

        while (!q.empty()) {
            id = q.front();
            q.pop();

            for (auto p : adj[id]) {
                if (dist[p] == INF) {
                    dist[p] = dist[id] + 1;
                    q.push(p);
                }
            }
        }

        // second pass, start from the most remote node id, collect last to get ID
        a = id;
        dist.assign(nn, INF);
        last.assign(nn, -1);
        dist[a] = 0;
        q.push(a);

        while (!q.empty()) {
            id = q.front();
            q.pop();

            for (auto p : adj[id]) {
                if (dist[p] == INF) {
                    dist[p] = dist[id] + 1;
                    last[p] = id;
                    q.push(p);
                }
            }
        }

        // a and id forms the diameter
        ans = dist[id];

        return ans;

        // construct the path of diamter in path
        vector<int> path;
        b = id;
        c = id;
        do {
            path.push_back(b);
            b = last[b];
        } while (b != -1);

        return ans;
    }
};


// Union-Find Disjoint Sets Library written in OOP manner, using both path compression and union by rank heuristics
// initialize: UnionFind UF(N)

class UnionFind {                                              // OOP style
private:
    vector<int> p, rank, setSize;
    // p = path toward the root of disjoint set; p[i] = i means it is root
    // rank = upper bound of the actual height of the tree; not reliable as accurate measure
    // setSize = size of each disjoint set

    int numSets;
public:
    UnionFind(int N) {
        setSize.assign(N, 1);
        numSets = N;
        rank.assign(N, 0);
        p.assign(N, 0);
        for (int i = 0; i < N; i++) p[i] = i;	// each belongs to its own set
    }

    int findSet(int i) {
        return (p[i] == i) ? i : (p[i] = findSet(p[i]));		// path compression: cut short of the path if possible
    }

    bool isSameSet(int i, int j) {
        return findSet(i) == findSet(j);
    }

    void unionSet(int i, int j) {
        if (!isSameSet(i, j)) {
            numSets--;
            int x = findSet(i), y = findSet(j);
            // rank is used to keep the tree short
            if (rank[x] > rank[y]) { p[y] = x; setSize[x] += setSize[y]; }
            else {
                p[x] = y; setSize[y] += setSize[x];
                if (rank[x] == rank[y]) rank[y]++;
            }
        }
    }

    int numDisjointSets() {		// # of disjoint sets
        return numSets;
    }

    int sizeOfSet(int i) {		// size of set
        return setSize[findSet(i)];
    }
};


#define MAXN 205000			// total # of prime numbers
#define MAXP 1001000		// highest number to test prime

int prime[MAXN];		// prime numbers: 2, 3, 5 ...
int lp[MAXP];		// lp[n] = n if n is prime; otherwise smallest prime factor of the number
int phi[MAXP];			// phii function

class prime_class {
public:
    long top;

    prime_class() {			// generate all prime under MAXP
        int i, i2, j;

        top = 0;
        lp[0] = 0;
        lp[1] = 1;
        for (i = 2; i < MAXP; i++) lp[i] = 0;

        top = 0;
        for (i = 2; i < MAXP; ++i) {
            if (lp[i] == 0) {
                lp[i] = i;
                prime[top++] = i;
            }
            for (j = 0; (j < top) && (prime[j] <= lp[i]) && (i * prime[j] < MAXP); ++j)
                lp[i * prime[j]] = prime[j];
        }
    }

    bool isprime(long long key)
    {
        if (key < MAXP)	return (lp[key] == key) && (key >= 2);
        else {
            int i;
            for (i = 0; (i < top) && (prime[i] * prime[i] <= key); i++)
                if (key % prime[i] == 0) return false;
            return true;
        }
    }

    unordered_map<int, int> factorize(int key) {
        unordered_map<int, int> ans;

        while (lp[key] != key) {
            ans[lp[key]]++;
            key /= lp[key];
        }
        if (key > 1) ans[key]++;

        return ans;
    }

    vector<int> mobius(int n) {     // generate mobius function of size n
        int i, j, k, ct, curr, cct, x, last;
        vector<int> mobius(n + 1);
        for (i = 1; i <= n; i++) {
            curr = i; ct = 0; last = -1;

            while (lp[curr] != curr) {
                x = lp[curr];
                if (x != last) {
                    cct = 1;
                    last = x;
                    ct++;
                }
                else {
                    if (++cct >= 2) {
                        mobius[i] = 0;
                        goto outer;
                    }

                }
                curr /= lp[curr];
            }
            if (curr > 1) {
                x = curr;
                if (x != last) {
                    cct = 1;
                    last = x;
                    ct++;
                }
                else {
                    if (++cct >= 2) {
                        mobius[i] = 0;
                        goto outer;
                    }

                }
            }

            if (ct % 2 == 0) mobius[i] = 1;
            else mobius[i] = -1;

        outer:;
        }

        return mobius;
    }

    int get_phi(int key) {	// calculate Euler's totient function, also known as phi-function
        int ans = key, last = 0;

        while (lp[key] != key) {
            if (lp[key] != last) {
                last = lp[key];
                ans -= ans / last;
            }
            key /= lp[key];
        }
        if ((key > 1) && (key != last)) ans -= ans / key;

        return ans;
    }

    void calc_all_phi(int n) {
        int i, j, k;
        for (int i = 1; i < n; i++) phi[i] = i;
        for (int i = 2; i < n; i++) {
            if (phi[i] == i) {
                for (int j = i; j < n; j += i) {
                    phi[j] /= i;
                    phi[j] *= i - 1;
                }
            }
        }
    }

    vector<pair<long long, long long>> factorize_full(long long key) {		// can be used to factorize numbers >= MAXP
        vector<pair<long long, long long>> ans;

        long i, ct, sq = sqrt(key) + 10;

        for (i = 0; (i < top) && (prime[i] <= sq); i++)
            if (key % prime[i] == 0) {
                ct = 0;
                while (key % prime[i] == 0) {
                    ct++;
                    key /= prime[i];
                }
                ans.push_back({ prime[i], ct });
            }
        if (key > 1) {
            ans.push_back({ key, 1 });
        }
        return ans;
    }

    void generate_divisors(int step, int v, vector<pair<int, int>>& fp, vector<int>& ans) {
        if (step < fp.size()) {
            generate_divisors(step + 1, v, fp, ans);
            for (int i = 1; i <= fp[step].second; i++) {
                v *= fp[step].first;
                generate_divisors(step + 1, v, fp, ans);
            }
        }
        else ans.push_back(v);
    }

    void generate_divisors_full(long long step, long long v, vector<pair<long long, long long>>& fp, vector<long long>& ans) {
        if (step < fp.size()) {
            generate_divisors_full(step + 1, v, fp, ans);
            for (int i = 1; i <= fp[step].second; i++) {
                v *= fp[step].first;
                generate_divisors_full(step + 1, v, fp, ans);
            }
        }
        else ans.push_back(v);
    }

    vector<int> get_divisors(int key) {
        unordered_map<int, int> f = factorize(key);
        int n = f.size();
        vector<pair<int, int>> fp;
        for (auto p : f) fp.push_back(p);
        vector<int> ans;
        generate_divisors(0, 1, fp, ans);
        return ans;
    }

    vector<long long> get_divisors_full(long long key) {
        vector<pair<long long, long long>> f = factorize_full(key);
        int n = f.size();
        vector<pair<long long, long long>> fp;
        for (auto p : f) fp.push_back(p);
        vector<long long> ans;
        generate_divisors_full(0, 1, fp, ans);
        return ans;
    }


    long long get_divisors_count(long long key) {
        vector<pair<long long, long long>> f = factorize_full(key);
        long long ans = 1;
        for (auto p : f) ans *= (p.second + 1);
        return ans;
    }

};


long long mul_inv(long long a, long long b)
{
    long long b0 = b, t, q;
    long long x0 = 0, x1 = 1;
    if (b == 1) return 1;
    while (a > 1) {
        q = a / b;
        t = b, b = a % b, a = t;
        t = x0, x0 = x1 - q * x0, x1 = t;
    }
    if (x1 < 0) x1 += b0;
    return x1;
}

long long division(long long a, long long b, long long p) {		// (a / b) mod p = ((a mod p) * (b^(-1) mod p)) mod p
    long long ans, inv;
    inv = mul_inv(b, p);
    ans = ((a % p) * inv) % p;
    return ans;
}


#define MP make_pair
#define PB push_back
#define F first
#define S second
#define LB lower_bound
#define UB upper_bound

#define SZ(x) ((int)x.size())
#define LEN(x) ((int)x.length())
#define ALL(x) begin(x), end(x)
#define RSZ resize
#define ASS assign
#define REV(x) reverse(x.begin(), x.end());

#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
#define FOR(i, n) for (int i = 0; i < n; i++) 
#define FOR1(i, n) for (int i = 1; i <= n; i++) 
#define SORT(x) sort(x.begin(), x.end())
#define RSORT(x) sort(x.rbegin(), x.rend())
#define SUM(x) accumulate(x.begin(), x.end(), 0LL)


#define IN(x) cin >> x;
#define OUT(x) cout << x << "\n";
#define INV(x, n) FOR(iiii, n) { cin >> x[iiii]; }
#define INV1(x, n) FOR1(iiii, n) { cin >> x[iiii]; }
#define OUTV(x, n) { FOR(iiii, n) { cout << x[iiii] << " "; } cout << "\n"; }
#define OUTV1(x, n) { FOR1(iiii, n) { cout << x[iiii] << " "; } cout << "\n"; }
#define OUTYN(x) { if (x) cout << "YES\n"; else cout << "NO\n"; }
#define OUTyn(x) { if (x) cout << "Yes\n"; else cout << "No\n"; }


#define MOD7 1000000007
#define MOD9 1000000009
#define MOD3 998244353




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

    LL n, i, j, k, nn;
    cin >> n;
    nn = n / 2;

    double a, b, c, x, xx;
    vector<double> w(n), s(n), v(n);

    FOR(i, n) {
        cin >> w[i] >> s[i];
    }

    a = 0.4; b = 2.1;
    while (b - a > 1E-7) {
        c = (a + b) / 2;

        FOR(i, n) {
            v[i] = c * w[i] - s[i];
        }
        SORT(v);

        bool valid = true;
        FOR(i, nn) {
            if (-v[i] - c * 20 < v[n - 1 - i] - 1E-6) {
                valid = false;
                break;
            }
        }

        if (valid) a = c;
        else b = c;
    }

    cout << setprecision(10) << fixed << a << "\n";


    return 0;
}

Kayaks CodeChef Solution in C


#include <stdio.h>
#include <math.h>
#include <stdlib.h>

int pair[100000][2];
int people;
double dist[100000];

int compare (const void * a, const void * b) {
  return ( *(double*)a - *(double*)b );
}

mergesort(double a[], int low, int high) {
	int mid;
	if(low<high) {
		mid=(low+high)/2;
		mergesort(a,low,mid);
		mergesort(a,mid+1,high);
		merge(a,low,high,mid);
	}
}
double c[100000];
merge(double a[], int low, int high, int mid) {
	int i, j, k;	
	i=low;
	j=mid+1;
	k=low;
	while((i<=mid)&&(j<=high)) {
		if(a[i]<a[j]) {
			c[k]=a[i];
			k++;
			i++;
		} else {
			c[k]=a[j];
			k++;
			j++;
		}
	}
	while(i<=mid) {
		c[k]=a[i];
		k++;
		i++;
	}
	while(j<=high) {
		c[k]=a[j];
		k++;
		j++;
	}
	for(i=low;i<k;i++) {
		a[i]=c[i];
	}
} 

void mysort(double data[], int N)
{
  int i, j;
  double v, t;

  if(N<=1) return;

  // Partition elements
  v = data[0];
  i = 0;
  j = N;
  for(;;)
  {
    while(data[++i] < v && i < N) { }
    while(data[--j] > v) { }
    if(i >= j) break;
    t = data[i]; data[i] = data[j]; data[j] = t;
  }
  t = data[i-1]; data[i-1] = data[0]; data[0] = t;
  mysort(data, i-1);
  mysort(data+i, N-i);
}

int isOk (double a) {
	double denominators = sqrt(a*a+1);
	//printf("%f, %f\n", a, denominators);
	int i;
	for (i=0; i<people; i++) 
		dist[i] = (a*pair[i][0]-pair[i][1]) / denominators;
		
	//qsort(dist, people, sizeof(double), compare);
	mysort(dist, people);
	//for (i=0; i<people; i++)
	//	printf("%f ", dist[i]);
	//printf("\n");
	
	for (i=0; i<<1<people; i++) 
		if (dist[i]+dist[people-1-i] > 0)
			return 0;
	return 1;
}
		
	
int main () {
		
	scanf("%d", &people);
	
	int i;
	for (i=0; i<people; i++) {
		scanf("%d %d", &pair[i][0], &pair[i][1]);
		pair[i][0] += 10;
	}
	
	double min = 0.4, max = 1.7, mid = 0;
	
	while (max-min>1e-8) {
		mid = (min + max) / 2;
		if (isOk(mid)) min = mid;
		else max = mid;
	}
	
	printf("%f\n", (min+max) / 2);
	return 0;
}	
		

Kayaks CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st ;
		int n = Integer.parseInt(br.readLine());
		int[] s = new int[n];
		int[] w = new int[n];
		for (int i = 0; i < n; i++) {
			st = new StringTokenizer(br.readLine());
			w[i] = Integer.parseInt(st.nextToken()) + 10;
			s[i] = Integer.parseInt(st.nextToken());
		}
		double max = (100.0 + 100.0) / (120.0);
		double min = (50.0 + 50.0) / (220.0);
		double mid = 0.0;
		double eps = 1e-8;
		while (max - min > eps) {
			mid = (max + min) / 2;
			if (isPossible(mid, w, s)) {
				min = mid;
			} else {
				max = mid;
			}
		}
		System.out.printf("%.7f",mid);
	}

	static boolean isPossible(double mid, int[] w, int[] s) {
		double[] delta = new double[w.length];
		for (int i = 0; i < w.length; i++) {
			delta[i] = s[i] - mid * w[i];
		}
		Arrays.sort(delta);
		for (int i = 0; i < delta.length; i++) {
			if (delta[i] + delta[delta.length - 1 - i] < 0)
				return false;
		}
		return true;
	}
}

Kayaks CodeChef Solution in C#

using System;
using System.Collections.Generic;


namespace CodeChef_200910_H2
{

    /// <summary>
    /// split persons ; group by weight & strength
    /// </summary>
    class PersonGroup : IComparable<PersonGroup>
    {        
        public int weight;
        public int strength;
        public int person_num;
        // when fill the min speed, some stength left.
        public decimal left_strength;

        public int CompareTo(PersonGroup other)
        {
            if (left_strength > other.left_strength) return 1;
            if (left_strength < other.left_strength) return -1;
            return 0;
        }
    }

   
    class CaseItem
    {
        int caseIndex;
        int person_number;
        int total_weight = 0;
        int total_strengh = 0;
        decimal aver_speed = 0;

        // for add person numbers quickly
        PersonGroup[,] groupTable = new PersonGroup[51, 51];
        // for sort by left_strength
        List<PersonGroup> personList = new List<PersonGroup>(51*51);

        private void buildIndex()
        {
            for (int weight = 0; weight <= 50; weight++)
            {
                for (int strength = 0; strength <= 50; strength++)
                {
                    PersonGroup p = new PersonGroup();
                    groupTable[weight, strength] = p;
                    p.weight = weight + 60;
                    p.strength = strength + 50;
                    personList.Add(p);
                }
            }
        }

        public CaseItem(int index)
        {
            this.buildIndex();

            caseIndex = index;
            person_number = int.Parse(System.Console.ReadLine());
            
            for (int i = 0; i < person_number; i++)
            {
                string s = Console.ReadLine();
                string[] a = s.Split(' ');
                int weight = int.Parse(a[0]) + 10;
                int strength = int.Parse(a[1]);

                groupTable[weight - 60, strength - 50].person_num++;

                total_weight += weight;
                total_strengh += strength;
            }
            aver_speed = decimal.Round((0.0M + total_strengh) / total_weight, 8);
        }        
        

        private decimal test_min_speed(decimal v)
        {
            foreach (PersonGroup pg in personList)
            {
                pg.left_strength = pg.strength - v * pg.weight;
            }

            QuickSort<PersonGroup>(personList, 0, personList.Count - 1);


            int start = 0;
            int end = personList.Count - 1;
            decimal min_v = int.MaxValue;            

            while (personList[start].person_num == 0) start++;
            while (personList[end].person_num == 0) end--;

            int min_start_index = start, min_end_index = end;

            int start_left = personList[start].person_num;
            int end_left = personList[end].person_num;
            PersonGroup pstart = personList[start];
            PersonGroup pend = personList[end];

            while (start <= end)
            {
                if (pstart.left_strength + pend.left_strength < min_v)
                {
                    min_v = pstart.left_strength + pend.left_strength;
                    min_start_index = start;
                    min_end_index = end;
                }

                if (start_left > end_left)
                {
                    start_left -= end_left;
                    end--;
                    pend = personList[end];
                    end_left = pend.person_num;
                }
                else if (start_left == end_left)
                {
                    start++;
                    end--;
                    pstart = personList[start];
                    pend = personList[end];
                    start_left = pstart.person_num;
                    end_left = pend.person_num;
                }
                else
                {
                    end_left -= start_left;
                    start++;
                    pstart = personList[start];
                    start_left = pstart.person_num;
                }
            }

            min_v = (0.0M + personList[min_start_index].strength + personList[min_end_index].strength) /
                (personList[min_start_index].weight + personList[min_end_index].weight);

            return decimal.Round(min_v, 8);
        }

        public void Execute()
        {
            decimal min_speed = aver_speed;
            decimal test_speed;
            do
            {
                test_speed = min_speed;
                min_speed = test_min_speed(test_speed);

            } while (min_speed != test_speed);

            System.Console.WriteLine(decimal.Round(min_speed, 6).ToString());
        }      
        

        public void QuickSort<T>(List<T> a, int low, int high)
            where T : IComparable<T>
        {
            if (high - low <= 0)
            {
                return;
            }
            else if (high - low == 1)
            {
                if (a[high].CompareTo(a[low]) < 0)
                {
                    T t = a[high];
                    a[high] = a[low];
                    a[low] = t;
                }
                return;
            }

            int mid = (low + high) >> 1;
            T pivot = a[mid];

            T t2 = a[mid];
            a[mid] = a[low];
            a[low] = t2;

            int up = low + 1;
            int down = high;

            do
            {
                while (up <= down && a[up].CompareTo(pivot) <= 0) up++;
                while (up <= down && a[down].CompareTo(pivot) > 0) down--;
                if (up < down)
                {
                    T t = a[up];
                    a[up] = a[down];
                    a[down] = t;
                }

            } while (up < down);


            a[low] = a[down];
            a[down] = pivot;

            if (low < down - 1)
            {
                QuickSort<T>(a, low, down - 1);
            }
            if (down + 1 < high)
            {
                QuickSort<T>(a, down + 1, high);
            }
        }
    }


    class Round
    {
        int case_num;
        CaseItem[] items;
        public Round()
        {
            case_num = 1;
            items = new CaseItem[case_num];

            for (int i = 0; i < case_num; i++)
            {
                items[i] = new CaseItem(i + 1);
            }
        }

        public void Execute()
        {
            foreach (CaseItem item in items)
            {
                item.Execute();
            }
        }
    }




    class Program
    {
        static void Main(string[] args)
        {
            //BuildDebug();
            (new Round()).Execute();
            // Debug();
        }

        static void BuildDebug()
        {
            using (System.IO.StreamWriter writer = new System.IO.StreamWriter("a.in"))
            {
                int n = 100000;

                Random r = new Random(1000000);
                writer.WriteLine(n);
                for (int i = 0; i < n; i++)
                {
                    int w = r.Next(n) % 51 + 50;
                    int s = r.Next(n) % 51 + 50;
                    writer.WriteLine(w.ToString() + " " + s.ToString());
                }
            }
        }

        static void Debug()
        {
            System.IO.TextReader stdin = System.Console.In;
            System.IO.TextWriter stdout = System.Console.Out;

            try
            {
                using (System.IO.StreamReader reader = new System.IO.StreamReader("a.in"))
                {
                    using (System.IO.StreamWriter writer = new System.IO.StreamWriter("out.txt"))
                    {

                        long datetime1 = DateTime.Now.Ticks;

                        System.Console.SetIn(reader);
                        System.Console.SetOut(writer);
                        (new Round()).Execute();

                        long datetime2 = DateTime.Now.Ticks;

                        DateTime datetime3 = DateTime.Now;

                        long seconds = (datetime2 - datetime1) / (datetime3.AddSeconds(1).Ticks - datetime3.Ticks);

                        System.Console.WriteLine(" second is : " + seconds.ToString());
                        System.Console.WriteLine(" ticks is : " + (datetime2 - datetime1).ToString());
                        System.Console.WriteLine(" ticks per seconds : " + (datetime3.AddSeconds(1).Ticks - datetime3.Ticks).ToString());
                    }
                }
            }
            finally
            {
                System.Console.SetIn(stdin);
                System.Console.SetOut(stdout);
            }
        }
    }
}

Kayaks CodeChef Solution in GO

package main

import (
	"bufio"
	"fmt"
	"os"
	"sort"
)

func main() {
	reader := bufio.NewReader(os.Stdin)

	n := readNum(reader)
	persons := make([][]int, n)

	for i := 0; i < n; i++ {
		persons[i] = readNNums(reader, 2)
	}

	res := solve(n, persons)

	fmt.Printf("%.7f\n", res)
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(n int, people [][]int) float64 {
	// strength >= 50 & <= 100
	// weight >= 50 & <= 100
	// so total unique pair would be <= 50 * 50
	pairs := make(map[Pair]int)
	for _, cur := range people {
		pairs[Pair{cur[1], cur[0]}]++
	}
	arr := make([]Pair, 0, len(pairs))
	for cur := range pairs {
		arr = append(arr, cur)
	}

	arr2 := make([]Pair, n)

	check := func(speed float64) bool {
		comp := Comp{speed, arr}

		sort.Sort(&comp)

		var p int

		for i := 0; i < len(arr); i++ {
			for j := 0; j < pairs[arr[i]]; j++ {
				arr2[p] = arr[i]
				p++
			}
		}

		for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
			a, b := arr2[i], arr2[j]
			if float64(a.first+b.first)-speed*float64(a.second+b.second+20) < 0 {
				return false
			}
		}
		return true
	}

	var lo, hi float64 = 0, 2.0

	for i := 0; i < 30; i++ {
		mid := (lo + hi) / 2
		if check(mid) {
			lo = mid
		} else {
			hi = mid
		}
	}

	return (lo + hi) / 2
}

type Pair struct {
	first  int
	second int
}

func (p Pair) Value(speed float64) float64 {
	return float64(p.first) - speed*float64(p.second)
}

type Comp struct {
	speed float64
	arr   []Pair
}

func (this *Comp) Len() int {
	return len(this.arr)
}

func (this *Comp) Less(i, j int) bool {
	a, b := this.arr[i], this.arr[j]
	return a.Value(this.speed) < b.Value(this.speed)
}

func (this *Comp) Swap(i, j int) {
	this.arr[i], this.arr[j] = this.arr[j], this.arr[i]
}
Kayaks CodeChef Solution Review:

In our experience, we suggest you solve this Kayaks CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Kayaks CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Kayaks CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *