Thursday, January 3, 2019

[codeforces] F. Make It Connected

Author            : Dipu Kumar Mohanto 
                    CSE, Batch - 6
                    BRUR.
Problem Statement : F. Make It Connected
Source            : codeforces
Category          : Graph Theory, Data Structure
Algorithm         : Minimum Spanning Tree, Kruskal Algorithm, Segment Tree
Verdict           : Accepted
#include "bits/stdc++.h"
 
using namespace std;
 
#define ll                    long long int
#define inf                   (ll)1e17
#define min3(a, b, c)         min(a, min(b, c))
#define min4(a, b, c, d)      min(a, min(b, min(c, d)))
 
static const int maxn = 2e5 + 5;
 
int father[maxn];
 
inline void init()
{
      for (int i = 1; i < maxn; i++) father[i] = i;
}
 
inline int findRep(int r)
{
      if (r == father[r]) return r;
      return father[r] = findRep(father[r]);
}
 
struct segmentTree
{
      ll minOne, minTwo;
      int minOnePosition, minTwoPosition;
      inline void assignLeaf(ll val, int pos, int ff)
      {
            minOne = val;
            minOnePosition = pos;
            minTwo = inf;
            minTwoPosition = -1;
      }
      inline void marge(const segmentTree &lft, const segmentTree &rgt)
      {
            ll cst[5];
            int pos[5];
            cst[1] = lft.minOne; pos[1] = lft.minOnePosition;
            cst[2] = lft.minTwo; pos[2] = lft.minTwoPosition;
            cst[3] = rgt.minOne; pos[3] = rgt.minOnePosition;
            cst[4] = rgt.minTwo; pos[4] = rgt.minTwoPosition;
            minOne = minTwo = inf;
            minOnePosition = minTwoPosition = -1;
            int fone = -1;
            int ftwo = -1;
            int take = -1;
            for (int i = 1; i <= 4; i++)
            {
                  if (cst[i] < minOne)
                  {
                        take = i;
                        minOne = cst[i];
                        minOnePosition = pos[i];
                        fone = findRep(pos[i]);
                  }
            }
            for (int i = 1; i <= 4; i++)
            {
                  if (i == take) continue;
                  int p = findRep(pos[i]);
                  if (cst[i] <= minTwo && p != fone)
                  {
                        minTwo = cst[i];
                        minTwoPosition = pos[i];
                        ftwo = p;
                  }
            }
      }
} Tree[maxn << 2];
 
 
struct node
{
      int u, v;
      ll w;
      node(int u = 0, int v = 0, ll w = 0) : u(u), v(v), w(w) {}
      inline friend bool operator < (const node A, const node B)
      {
            return A.w < B.w;
      }
};
 
using pii = pair <int , int>;
 
map <pii, ll> mapper;
ll cost[maxn];
vector <node> graph;
 
inline void build(int node, int a, int b)
{
      if (a == b)
      {
            Tree[node].assignLeaf(cost[a], a, father[a]);
            return;
      }
      int lft = node << 1;
      int rgt = lft | 1;
      int mid = (a + b) >> 1;
      build(lft, a, mid);
      build(rgt, mid+1, b);
      Tree[node].marge(Tree[lft], Tree[rgt]);
}
 
inline void update(int node, int a, int b, int pos, int p)
{
      if (a > b or a > pos or b < pos) return;
      if (a >= pos && b <= pos)
      {
            Tree[node].assignLeaf(cost[pos], pos, p);
            return;
      }
      int lft = node << 1;
      int rgt = lft | 1;
      int mid = (a + b) >> 1;
      update(lft, a, mid, pos, p);
      update(rgt, mid+1, b, pos, p);
      Tree[node].marge(Tree[lft], Tree[rgt]);
}
 
inline segmentTree query(int node, int a, int b, int i, int j)
{
      if (a == i && b == j) return Tree[node];
      int lft = node << 1;
      int rgt = lft | 1;
      int mid = (a + b) >> 1;
      segmentTree p, q, res;
      if (j <= mid)
      {
            res = query(node, a, mid, i, j);
      }
      else if (i > mid)
      {
            res = query(node, mid+1, b, i, j);
      }
      else
      {
            p = query(node, a, mid, i, mid);
            q = query(node, mid+1, b, mid+1, j);
            res.marge(p, q);
      }
      return res;
}
 
int main()
{
      //freopen("in.txt", "r", stdin);
      int n, m;
      scanf("%d %d", &n, &m);
      for (int i = 1; i <= n; i++) scanf("%lld", &cost[i]);
      for (int i = 1; i <= m; i++)
      {
            int u, v;
            ll w;
            scanf("%d %d %lld", &u, &v, &w);
            if (cost[u] + cost[v] > w) graph.emplace_back(u, v, w);
      }
      init();
      build(1, 1, n);
      int taken = 0;
      while (taken < n-1)
      {
            segmentTree qry = query(1, 1, n, 1, n);
            int u = qry.minOnePosition;
            int v = qry.minTwoPosition;
            int p = findRep(qry.minOnePosition);
            int q = findRep(qry.minTwoPosition);
            ll costFromST = inf;
            if (p != q)
            {
                  costFromST = qry.minOne + qry.minTwo;
            }
            if (costFromST == inf)
            {
                  break;
            }
            else
            {
                  father[q] = p;
                  update(1, 1, n, u, p);
                  update(1, 1, n, v, p);
                  graph.emplace_back(u, v, costFromST);
                  taken++;
            }
 
      }
      init();
      sort(graph.begin(), graph.end());
      taken = 0;
      ll tcost = 0;
      for (node g : graph)
      {
            int u = g.u;
            int v = g.v;
            ll w = g.w;
            int p = findRep(u);
            int q = findRep(v);
            if (p != q)
            {
                  father[q] = p;
                  tcost += w;
                  taken++;
            }
            if (taken == n-1) break;
      }
      printf("%lld", tcost);
}

[codeforces] D. Easy Problem

Author            : Dipu Kumar Mohanto 
                    CSE, Batch - 6
                    BRUR.
Problem Statement : D. Easy Problem
Source            : codeforces
Category          : Dynamic Programing
Algorithm         : DP on subsequence
Verdict           : Accepted
#include "bits/stdc++.h"
 
using namespace std;
 
#define FI              freopen("in.txt", "r", stdin)
#define FO              freopen("out.txt", "w", stdout)
#define FAST            ios_base::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
 
#define FOR(i, n)       for (int i = 1; i <= n; i++)
#define For(i, n)       for (int i = 0; i < n; i++)
#define ROF(i, n)       for (int i = n; i >= 1; i--)
#define Rof(i, n)       for (int i = n-1; i >= 0; i--)
#define FORI(i, n)      for (auto i : n)
 
#define ll              long long
#define ull             unsigned long long
#define vi              vector <int>
#define vl              vector <ll>
#define pii             pair <int, int>
#define pll             pair <ll, ll>
#define mk              make_pair
#define ff              first
#define ss              second
#define eb              emplace_back
#define em              emplace
#define pb              push_back
#define ppb             pop_back
#define All(a)          a.begin(), a.end()
#define memo(a, b)      memset(a, b, sizeof a)
#define Sort(a)         sort(All(a))
#define ED(a)           Sort(a), a.erase(unique(All(a)), a.end())
#define rev(a)          reverse(All(a))
#define sz(a)           (int)a.size()
#define max3(a, b, c)   max(a, max(b, c))
#define min3(a, b, c)   min(a, min(b, c))
#define maxAll(a)       *max_element(All(a))
#define minAll(a)       *min_element(All(a))
#define allUpper(a)     transform(All(a), a.begin(), :: toupper)
#define allLower(a)     transform(All(a), a.begin(), :: tolower)
#define endl            '\n'
#define nl              puts("")
#define ub              upper_bound
#define lb              lower_bound
#define Exp             exp(1.0)
#define PIE             2*acos(0.0)
#define Sin(a)          sin(((a)*PIE)/180.0)
#define EPS             1e-9
 
// Important Functions
// mo compare function : friend bool operator < (mo p, mo q) { int pb = p.l / block; int qb = q.l / block; if (pb != qb) return p.l < q.l; return (p.r < q.r) ^ (p.l / block % 2); }
// factorial MOD inverse : ll inv[maxn]; inline ll factorialInverse() { inv[1] = 1; for (int i = 2; i < maxn; i++) inv[i] = (MOD � (MOD / i)) * inv[MOD % i) % MOD; }
 
/**
  * uses of PBDS:
  * 1) *X.find_by_order(k) : returns k'th element
  * 2) X.order_of_key(k)   : count total element less than k
  * 3) All other operations same as set
**/
#include "ext/pb_ds/assoc_container.hpp"
#include "ext/pb_ds/tree_policy.hpp"
using namespace __gnu_pbds;
 
template <typename T> using orderset = tree <T, null_type, less <T>, rb_tree_tag, tree_order_statistics_node_update>;
 
/**
  * uses of rope data structure:
  * Initialize                 : rope <data_type> Rope;
  * Insert single element      : Rope.push_back()
  * Insert a block of elements : Rope.insert(position after insert, newRope)
  * Erase a block of elements  : Rope.erase(starting position of deletion, size of deletion)
  * Other Operations           : Same as std::vector
  * Iterator                   : Rope.mutable_begin(), Rope.mutable_end(), Rope.mutable_rbegin(), Rope.mutable_rend()
  * Caution                    : Never use -- Rope.begin() iterator
**/
#include "ext/rope"
using namespace __gnu_cxx;
 
// rope <int> Rope;
 
// int dr[] = {1, -1, 0, 0}; // 4 Direction
// int dc[] = {0, 0, 1, -1};
// int dr[] = {0, 0, 1, -1, 1, 1, -1, -1}; // 8 Direction
// int dc[] = {1, -1, 0, 0, 1, -1, 1, -1};
// int dr[] = {-1, 1, -2, -2, -1, 1, 2, 2}; // knight Moves
// int dc[] = {-2, -2, -1, 1, 2, 2, 1, -1};
 
#define trace1(x)                           cerr << #x << ": " << x << endl;
#define trace2(x, y)                        cerr << #x << ": " << x << " | " << #y << ": " << y << endl;
#define trace3(x, y, z)                     cerr << #x << ": " << x << " | " << #y << ": " << y << " | " << #z << ": " << z << endl;
#define trace4(a, b, c, d)                  cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << endl;
#define trace5(a, b, c, d, e)               cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << endl;
#define trace6(a, b, c, d, e, f)            cerr << #a << ": " << a << " | " << #b << ": " << b << " | " << #c << ": " << c << " | " << #d << ": " << d << " | " << #e << ": " << e << " | " << #f << ": " << f << endl;
 
inline int setbit(int mask, int pos)        { return mask |= (1 << pos); }
inline int resetbit(int mask, int pos)      { return mask &= ~(1 << pos); }
inline int togglebit(int mask, int pos)     { return mask ^= (1 << pos); }
inline bool checkbit(int mask, int pos)     { return (bool)(mask & (1 << pos)); }
 
#define popcount(mask)                       __builtin_popcount(mask) // count set bit
#define popcountLL(mask)                     __builtin_popcountll(mask) // for long long
 
inline int read()                           { int a; scanf("%d", &a); return a; }
inline ll readLL()                          { ll a; scanf("%lld", &a); return a; }
inline double readDD()                      { double a; scanf("%lf", &a); return a; }
 
template <typename T> string toString(T num) { stringstream ss; ss << num; return ss.str(); }
int toInt(string s)                          { int num; istringstream iss(s); iss >> num; return num;  }
ll toLLong(string s)                         { ll num; istringstream iss(s); iss >> num; return num; }
 
#define inf             1e17
#define mod             1000000007
 
static const int maxn = 1e5 + 5;
static const int logn = 18;
 
ll dp[maxn][5];
bool memoize[maxn][5];
string text, pat;
int lenText, lenPat;
 
inline ll subsequence(int i, int j)
{
      if (j == lenPat) return 1;
      if (i >= lenText) return 0;
      ll &ret = dp[i][j];
      bool &mem = memoize[i][j];
      if (mem) return ret;
      mem = 1;
      ll sum = 0;
      if (text[i] == pat[j])
      {
            sum += subsequence(i+1, j+1);
            sum += subsequence(i+1, j);
      }
      else
      {
            sum += subsequence(i+1, j);
      }
      return ret = sum;
}
 
ll dp2[maxn][5];
bool memoize2[maxn][5];
ll cost[maxn];
 
inline ll minimumCost(int i, int j)
{
      if (j == lenPat) return inf;
      if (i >= lenText) return 0;
      ll &ret = dp2[i][j];
      bool &mem = memoize2[i][j];
      if (mem) return ret;
      mem = 1;
      ll sum = inf;
      if (text[i] != pat[j])
      {
            sum = minimumCost(i+1, j);
      }
      else
      {
            ll sum1 = cost[i] + minimumCost(i+1, j);
            ll sum2 = minimumCost(i+1, j+1);
            sum = min(sum1, sum2);
      }
      return ret = sum;
}
 
int main()
{
      //FI;
 
      cin >> lenText;
      lenPat = 4;
      pat = "hard";
      cin >> text;
      ll koyta = subsequence(0, 0);
      if (koyta == 0)
      {
            cout << "0";
            return 0;
      }
      for (int i = 0; i < lenText; i++) cin >> cost[i];
      ll mini = minimumCost(0, 0);
      cout << mini;
}

[toph.co] Just Another Range Query

Author            : Dipu Kumar Mohanto 
                    CSE, Batch - 6
                    BRUR.
Problem Statement : Just Another Range Query
Source            : toph.co
Category          : Data Structure
Algorithm         : Implicit Segment Tree, Lazy Propagation
Verdict           : Accepted
#include "bits/stdc++.h"
 
using namespace std;
 
#define ll              long long
 
struct node
{
      ll sum, lazy;
      node *lft, *rgt;
      node() : sum(0), lazy(0), lft(nullptr), rgt(nullptr) {}
 
      ~node()
      {
            delete lft;
            delete rgt;
      }
};
 
typedef node*       pnode;
 
inline void updateLazy(pnode root, ll a, ll b, ll val)
{
      root->sum += (b - a + 1) * val;
      root->lazy += val;
}
 
inline void updateNode(pnode root, ll a, ll b)
{
      ll mid = (a + b) >> 1;
      if (root->lft == nullptr) root->lft = new node();
      root->lft->lazy += root->lazy;
      root->lft->sum += (mid - a + 1) * root->lazy;
 
      if (root->rgt == nullptr) root->rgt = new node();
      root->rgt->lazy += root->lazy;
      root->rgt->sum += (b - mid) * root->lazy;
 
      root->lazy = 0;
}
 
inline void update(pnode root, ll a, ll b, ll i, ll j, ll val)
{
      if (a == i && b == j)
      {
            updateLazy(root, a, b, val);
            return;
      }
      if (root->lazy != 0)
      {
            updateNode(root, a, b);
      }
      ll mid = (a + b) >> 1;
      if (root->lft == nullptr) root->lft = new node();
      if (root->rgt == nullptr) root->rgt = new node();
      if (j <= mid)
      {
            update(root->lft, a, mid, i, j, val);
      }
      else if (i > mid)
      {
            update(root->rgt, mid+1, b, i, j, val);
      }
      else
      {
            update(root->lft, a, mid, i, mid, val);
            update(root->rgt, mid+1, b, mid+1, j, val);
      }
      root->sum = root->lft->sum + root->rgt->sum;
}
 
inline ll query(pnode root, ll a, ll b, ll i, ll j)
{
      if (a == i && b == j) return root->sum;
      if (root->lazy != 0)
      {
            updateNode(root, a, b);
      }
      ll mid = (a + b) >> 1;
      ll res = 0;
      if (root->lft == nullptr) root->lft = new node();
      if (root->rgt == nullptr) root->rgt = new node();
      if (j <= mid)
      {
            res += query(root->lft, a, mid, i, j);
      }
      else if (i > mid)
      {
            res += query(root->rgt, mid+1, b, i, j);
      }
      else
      {
            res += query(root->lft, a, mid, i, mid);
            res += query(root->rgt, mid+1, b, mid+1, j);
      }
      return res;
}
 
inline ll getSum(ll l, ll r)
{
      --l;
      ll suml = (1LL * l * (l+1)) / 2;
      ll sumr = (1LL * r * (r+1)) / 2;
      return sumr - suml;
}
 
inline void clean(pnode root)
{
      if (root == nullptr) return;
      clean(root->lft);
      clean(root->rgt);
      delete root;
}
 
 
int main()
{
      //freopen("in.txt", "r", stdin);
 
      ios_base::sync_with_stdio(false);
      cin.tie(nullptr);
 
      pnode root = new node();
      ll n, q;
      cin >> n >> q;
      while (q--)
      {
            ll type;
            cin >> type;
            if (type == 1)
            {
                  ll l, r;
                  ll val;
                  cin >> l >> r >> val;
                  if (l > r) swap(l, r);
                  update(root, 1, n, l, r, val);
            }
            else
            {
                  ll l, r;
                  cin >> l >> r;
                  if (l > r) swap(l, r);
                  ll tsum = getSum(l, r) - query(root, 1, n, l, r);
                  cout << tsum << endl;
            }
      }
}