跳到正文

剪贴板

剪贴板 4ep52wjf

原文
剪贴板信息

剪贴板信息

收录
更新

CC++ 常用模板


堆区内存分配器

C++
template <typename Typex>
inline void* Malc(const Typex& Value, const unsigned& S) {
  Typex* arr = new Typex[S];
  for (unsigned i = 0; i < S; i++)
    arr[i] = Value;
  return arr;
}

template <typename Typex, typename... EType>
inline void* Malc(const Typex& Value, const unsigned& S, const EType&... E) {
  Typex** arr = new Typex*[S];
  for (unsigned i = 0; i < S; i++)
    arr[i] = (Typex*)Malc<Typex>(Value, E...);
  return arr;
}

食用方法:auto arr = Malc</* 类型 */>(/* 初始值 */, /* 大小, 几维填几个*/)

查找

C++
template <typename comp>
inline int fs(const int& MAX, const comp& cmp) {
  int qloc = 0;
  for (int pew = MAX; pew; pew >>= 1)
    if (cmp(qloc + pew))
      qloc += pew;
  return qloc;
}

对拍

C++
g++ #MAKE.cxx -std=c++14 -o #MAKE
@echo off
if errorlevel = 1 goto end
@echo on
g++ #1.cxx -std=c++14 -o #1
@echo off
if errorlevel = 1 goto end
@echo on
g++ #2.cxx -std=c++14 -o #2
@echo off
if errorlevel = 1 goto end
@echo on
:next_test
#MAKE.exe > input
#2.exe < input > #2
#1.exe < input > #1
fc #1 #2
@echo off
if errorlevel = 1 goto end
@echo on
goto next_test
:end
echo Error
pause

高精度

C++
#include <cassert>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>

using namespace std;

class BigInteger {
  static const int BASE = 100000000;
  static const int WIDTH = 8;

 public:
  vector<int> s;

  BigInteger& clean() {
    while (!s.back() && s.size() > 1)
      s.pop_back();
    return *this;
  }

  BigInteger(unsigned long long num = 0) { *this = num; }

  BigInteger(string s) { *this = s; }

  BigInteger& operator=(long long num) {
    s.clear();
    do {
      s.push_back(num % BASE);
      num /= BASE;
    } while (num > 0);
    return *this;
  }

  BigInteger& operator=(const string& str) {
    s.clear();
    int x, len = (str.length() - 1) / WIDTH + 1;
    for (int i = 0; i < len; i++) {
      int end = str.length() - i * WIDTH;
      int start = max(0, end - WIDTH);
      sscanf_s(str.substr(start, end - start).c_str(), "%d", &x);
      s.push_back(x);
    }
    return this->clean();
  }

  BigInteger operator+(const BigInteger& b) const {
    BigInteger c;
    c.s.clear();
    for (int i = 0, g = 0;; i++) {
      if (g == 0 && i >= s.size() && i >= b.s.size())
        break;
      int x = g;
      if (i < s.size())
        x += s[i];
      if (i < b.s.size())
        x += b.s[i];
      c.s.push_back(x % BASE);
      g = x / BASE;
    }
    return c;
  }

  BigInteger operator-(const BigInteger& b) const {
    assert(b <= *this);
    BigInteger c;
    c.s.clear();
    for (int i = 0, g = 0;; i++) {
      if (g == 0 && i >= s.size() && i >= b.s.size())
        break;
      int x = s[i] + g;
      if (i < b.s.size())
        x -= b.s[i];
      if (x < 0) {
        g = -1;
        x += BASE;
      } else
        g = 0;
      c.s.push_back(x);
    }
    return c.clean();
  }

  BigInteger operator*(const BigInteger& b) const {
    int i, j;
    unsigned long long g;
    vector<unsigned long long> v(s.size() + b.s.size(), 0);
    BigInteger c;
    c.s.clear();
    for (i = 0; i < s.size(); i++)
      for (j = 0; j < b.s.size(); j++)
        v[i + j] += unsigned long long(s[i]) * b.s[j];
    for (i = 0, g = 0;; i++) {
      if (g == 0 && i >= v.size())
        break;
      unsigned long long x = v[i] + g;
      c.s.push_back(x % BASE);
      g = x / BASE;
    }
    return c.clean();
  }

  BigInteger operator/(const BigInteger& b) const {
    assert(b > 0);
    BigInteger c = *this, m;
    for (int i = s.size() - 1; i > -1; i--) {
      m = m * BASE + s[i];
      c.s[i] = bsearch(b, m);
      m -= b * c.s[i];
    }
    return c.clean();
  }

  BigInteger operator%(const BigInteger& b) const {
    BigInteger c = *this;
    BigInteger m;
    for (int i = s.size() - 1; i > -1; i--) {
      m = m * BASE + s[i];
      c.s[i] = bsearch(b, m);
      m -= b * c.s[i];
    }
    return m;
  }

  int bsearch(const BigInteger& b, const BigInteger& m) const {
    int L = 0, R = BASE - 1, x;
    while (1) {
      x = (L + R) >> 1;
      if (b * x <= m) {
        if (b * (x + 1) > m)
          return x;
        else
          L = x;
      } else
        R = x;
    }
  }

  BigInteger& operator+=(const BigInteger& b) {
    *this = *this + b;
    return *this;
  }

  BigInteger& operator-=(const BigInteger& b) {
    *this = *this - b;
    return *this;
  }

  BigInteger& operator*=(const BigInteger& b) {
    *this = *this * b;
    return *this;
  }

  BigInteger& operator/=(const BigInteger& b) {
    *this = *this / b;
    return *this;
  }

  BigInteger& operator%=(const BigInteger& b) {
    *this = *this % b;
    return *this;
  }

  bool operator<(const BigInteger& b) const {
    if (s.size() != b.s.size())
      return s.size() < b.s.size();
    for (int i = s.size() - 1; i; i--)
      if (s[i] != b.s[i])
        return s[i] < b.s[i];
    return s[0] < b.s[0];
  }
  bool operator>(const BigInteger& b) const { return b < *this; }
  bool operator<=(const BigInteger& b) const { return !(b < *this); }
  bool operator>=(const BigInteger& b) const { return !(*this < b); }
  bool operator!=(const BigInteger& b) const { return b < *this || *this < b; }
  bool operator==(const BigInteger& b) const {
    return !(b < *this) && !(b > *this);
  }
};

ostream& operator<<(ostream& out, const BigInteger& x) {
  out << x.s.back();
  for (int i = x.s.size() - 2; i > -1; i--) {
    char buf[20];
    sprintf_s(buf, "%08d", x.s[i]);
    for (int j = 0; j < strlen(buf); j++)
      out << buf[j];
  }
  return out;
}

istream& operator>>(istream& in, BigInteger& x) {
  string s;
  if (!(in >> s))
    return in;
  x = s;
  return in;
}

dijkstradijkstra

C++
#include <iostream>
#include <queue>
#include <cstring>

using namespace std;

struct CE {
    int to, dist, next;
    CE() {}
    CE(int to, int dist, int next) : to(to), dist(dist), next(next) {}
} e[500005];

struct TLE {
    int dist, pos;
    TLE() {}
    TLE(int dist, int pos) : dist(dist), pos(pos) {}
    inline bool operator < (const TLE& comp) const {
        return comp.dist < dist;
    }
};

bool vis[100001];
int head[100001], dist[100001];
int n, m;
priority_queue<TLE> heap;

inline void add_edge(int u, int v, int dist) {
    static int tot = 0;
    e[++tot] = CE(v, dist, head[u]);
    head[u] = tot;
}

inline void dijkstra(int s) {
    dist[s] = 0;
    for (heap.emplace(0, s); !heap.empty(); heap.pop()) {
        if (vis[heap.top().pos])
            continue;
        vis[heap.top().pos] = true;
        for (int i = head[heap.top().pos]; i; i = e[i].next)
            if (dist[e[i].to] > dist[heap.top().pos] + e[i].dist) {
                dist[e[i].to] = dist[heap.top().pos] + e[i].dist;
                if (!vis[e[i].to])
                    heap.emplace(dist[e[i].to], e[i].to);
            }
    }
}

int main() {
    int s;
    cin >> n >> m >> s;
    for (int i = 1; i <= n; i++)
        dist[i] = 0x7fffffff;
    for (int i = 0; i < m; i++) {
        int u, v, dist;
        cin >> u >> v >> dist;
        add_edge(u, v, dist);
    }
    dijkstra(s);
    for (int i = 1; i <= n; i++)
        cout << dist[i] << ' ';
    return 0;
}

spfaspfa

C++
#include "iostream"
#include "queue"

using namespace std;

struct CE {
  int to, dist, next;
  CE() {}
  CE(int to, int dist, int next) : to(to), dist(dist), next(next) {}
} e[500005];

bool vis[10001];
int dist[10001], head[10001];
int n;

void add_edge(const int& u, const int& v, const int& dist) {
  static int tot = 0;
  e[++tot] = CE(v, dist, head[u]);
  head[u] = tot;
}

void spfa(const int& s) {
  queue<int> Q;
  for (int i = 1; i <= n; i++)
    dist[i] = 0x7fffffff;
  dist[s] = 0;
  vis[s] = true;
  for (Q.push(s); Q.size(); Q.pop()) {
    vis[Q.front()] = false;
    for (int i = head[Q.front()]; i; i = e[i].next) {
      if (dist[e[i].to] > dist[Q.front()] + e[i].dist) {
        dist[e[i].to] = dist[Q.front()] + e[i].dist;
        if (!vis[e[i].to]) {
          vis[e[i].to] = true;
          Q.push(e[i].to);
        }
      }
    }
  }
}

int main() {
  int m, s;
  cin >> n >> m >> s;
  for (int i = 0; i < m; i++) {
    int u, v, dist;
    cin >> u >> v >> dist;
    add_edge(u, v, dist);
  }
  spfa(s);
  for (int i = 1; i <= n; i++)
    cout << dist[i] << ' ';
  return 0;
}

快速幂

C++
inline int qpow(int x, int y, int mod) {
  int pew;
  for (pew = 1; y; y >>= 1) {
    if (y & 1)
      pew = pew * x % mod;
    x = x * x % mod;
  }
  return pew;
}

并查集

C++
#include <iostream>

using namespace std;

int b[10001];

inline void init(int n) {
  for (int i = 1; i <= n; i++)
  	b[i] = i;
}

inline int find(int u) {
  return (b[u] == u ? u : b[u] = find(b[u]));
}

inline void merge(int u, int v) {
  b[find(v)] = find(u);
}

int main(){
  int n, m;
  cin >> n >> m;
  init(n);
  for (int i = 0; i < m; i++) {
  	int op;
  	cin >> op;
  	if (op == 1) {
	  int x, y;
	  cin >> x >> y;
	  merge(x, y);
	} else {
	  int x, y;
	  cin >> x >> y;
	  cout << (find(x) == find(y) ? "Y\n" : "N\n");
	}
  }
  return 0;
}

内存池

C++
class Mempool {
  const static int Block_Size = 1024;
  const static int Item_Size = 16;

  struct Item_Node {
    struct Item_Node* next;
    char data[Item_Size - sizeof(Item_Node*)];
  };

  struct Block_Node {
    struct Block_Node* next;
    Item_Node data[Block_Size / Item_Size];
  };

  Block_Node* BlockNodeHead;
  Item_Node* freeItemNodeHead;

 public:
  Mempool() : BlockNodeHead(0), freeItemNodeHead(0) {}
  ~Mempool() {
    for (Block_Node* tmp = BlockNodeHead; tmp; tmp = BlockNodeHead) {
      BlockNodeHead = BlockNodeHead->next;
      delete tmp;
    }
  }

  void* Alloc() {
    if (!freeItemNodeHead) {
      Block_Node* tmpBlockNode = new Block_Node;
      if (!tmpBlockNode) {
        perror("No memory!/n");
        exit(1);
      }
      if (BlockNodeHead) {
        tmpBlockNode->next = BlockNodeHead;
        BlockNodeHead = tmpBlockNode;
      } else {
        BlockNodeHead = tmpBlockNode;
        BlockNodeHead->next = NULL;
      }
      freeItemNodeHead = &(tmpBlockNode->data[0]);
      int i;
      for (i = 0; i < Block_Size / Item_Size - 1; i++)
        tmpBlockNode->data[i].next = &(tmpBlockNode->data[i + 1]);
      tmpBlockNode->data[i].next = NULL;
    }
    Item_Node* allocItemNode = freeItemNodeHead;
    freeItemNodeHead = freeItemNodeHead->next;
    return allocItemNode;
  }

  void Free(void* p) {
    Item_Node* tmpItemNode = static_cast<Item_Node*>(p);
    tmpItemNode->next = freeItemNodeHead;
    freeItemNodeHead = tmpItemNode;
  }
};

向量

C++
template<typename Typex>
class memory {
	unsigned _alocked;
	Typex* elespace;
public:
	using iterator = Typex*;
	memory(const unsigned& size) {
		elespace = new Typex[_alocked = size];
	}

	memory(const unsigned& size, const Typex& val) {
		elespace = new Typex[_alocked = size];
		for (unsigned i = 0; i < size; i++) {
			elespace[i] = val;
		}
	}

	inline unsigned size() {
		return _alocked;
	}

	inline void resize(const unsigned& size) {
		auto tmp = new Typex[_alocked];
		for (unsigned i = 0; i < _alocked; i++)
			tmp[i] = elespace[i];
		delete[] elespace;
		elespace = new Typex[size];
		for (unsigned i = 0; i < _alocked; i++)
			elespace[i] = tmp[i];
		_alocked = size;
	}

	inline void operator () (const unsigned& size) {
		delete[] elespace;
		elespace = new Typex[_alocked = size];
	}

	inline void operator () (const unsigned& size, const Typex& val) {
		delete[] elespace;
		elespace = new Typex[_alocked = size];
		for (unsigned i = 0; i < size; i++) {
			elespace[i] = val;
		}
	}

	inline Typex& operator [] (const unsigned& x) {
		return elespace[x];
	}

	inline void push(const Typex& val) {
		resize(_alocked + 1);
		elespace[_alocked - 1] = val;
	}

	inline void pop() {
		resize(_alocked - 1);
	}

	inline Typex* begin() {
		return elespace;
	}

	inline Typex* end() {
		return elespace + _alocked;
	}

	inline bool empty() {
		return _alocked;
	}

	~memory() {
		delete[] elespace;
	}
};

拿 stlstl 的哈希实现的哈希

C++
template <typename Typex, typename AType = unsigned>
class arv {
  hash<string> HT;
  unordered_map<unsigned long long, Typex> bt;

  template <typename... TT>
  inline string to_hash(const AType& x, const TT&... y) {
    return to_string(x) + to_hash(y...);
  }

  inline string to_hash() { return ""; }

 public:
  template <typename T, typename... TT>
  inline Typex& operator()(const T& x, const TT&... y) {
    return bt[HT(to_hash(x) + to_hash(y...))];
  }
};

自制命令行

C++
#include <iostream>
#include <cstring>

using namespace std;

int main() {
	string type;
	cin >> type;
	if (type == "PS:")
		system("PowerShell");
	getchar();
	for (char com[1000]; cout << "RB - Cmd >: " && gets_s(com); com[strlen(com)] = 0, system(com));
	return 0;
}

归并排序

C++
template<typename _element, typename _sorter, typename _compare>
inline void merger(const _sorter &l, _sorter r, _element *sorter, _element *temp, _compare compare) {
    if (l == r) {
        return;
    }
    int mid = (l + r) >> 1;
    merger(l, mid++, sorter, temp, compare);
    merger(mid, r++, sorter, temp, compare);
    int pointer = l, pointer_ = mid, p = l;
    while (pointer < mid && pointer_ < r)
        temp[p++] = (compare(sorter[pointer_], sorter[pointer]) ? sorter[pointer_++] : sorter[pointer++]);
    while (pointer < mid)
        temp[p++] = sorter[pointer++];
    while (pointer_ < r)
        temp[p++] = sorter[pointer_++];
    for (int i = l; i < r; i++) {
        sorter[i] = temp[i];
    }
}

template<typename _element, typename _sorter, typename _compare>
inline void merge(_element *a, _sorter l, _sorter r, _compare compare) {
    auto *temp = new _element [--r - l];
    merger(l, r, a, temp, compare);
}

手写哈希

C++
template <typename FType,
          typename EType,
          const int M1,
          const int M2,
          const int P = 2147483647>
class Hash_Map {
  unsigned A, B;
  struct Tbucket {
    unsigned A, B;
    EType* Element = new EType[M2];
  }* Bucket = new Tbucket[M1];

  inline int Hash(const unsigned& a,
                  const unsigned& b,
                  const FType& K,
                  const int& Mx) {
    return ((a * K + b) % P) % Mx;
  }

 public:
  inline Hash_Map() {
    srand(time(0));
    hash<int> Ht;
    A = Ht(-1) % 100000;
    B = rand() % 50000000;
    for (int i = 0; i < M1; i++) {
      Bucket[i].A = Ht(i) % 100000;
      Bucket[i].B = rand() % 50000000;
    }
  }

  inline EType& operator[](const FType& K) {
    int Val = Hash(A, B, K, M1);
    return Bucket[Val].Element[Hash(Bucket[Val].A, Bucket[Val].B, K, M2)];
  }
};

快读 #1

C++
namespace nqio{
  const unsigned R=4e5,W=4e5;char*a,*b,i[R],o[W],*c=o,*d=o+W,h[40],*p=h,y;
  bool s;
  struct q{void r(char&x){x=a==b&&(b=(a=i)+fread(i,1,R,stdin),a==b)?-1:*a++;}
           void f(){fwrite(o,1,c-o,stdout);c=o;}~q(){f();}
           void w(char x){*c=x;
                       if(++c==d)f();}
           q&operator>>(char&x){do r(x);while(x<=32);return*this;}q&operator>>(char*x){do r(*x);while(*x<=32);while(*x>32)r(*++x);*x=0;return*this;}template<typename t>q&operator>>(t&x){for(r(y),s=0;!isdigit(y);r(y))s|=y==45;if(s)for(x=0;isdigit(y);r(y))x=x*10-(y^48);else for(x=0;isdigit(y);r(y))x=x*10+(y^48);return*this;}q&operator<<(char x){w(x);return*this;}q&operator<<(char*x){while(*x)w(*x++);return*this;}q&operator<<(const char*x){while(*x)w(*x++);return*this;}template<typename t>q&operator<<(t x){if(!x)w(48);else if(x<0)for(w(45);x;x/=10)*p++=48|-(x%10);else for(;x;x/=10)*p++=48|x%10;while(p!=h)w(*--p);return*this;}}qio;}using nqio::qio;

快读 #2

C++
class buf {
private:
    int ch;
    bool bol;
public:
    inline buf & operator >> (int & _) {
        ch = getchar();
        bol = false;
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        if(bol)
            _ = -_;
        return *this;
    }
    inline buf & operator >> (bool & _) {
        ch = getchar();
        while('0' > ch || ch > '9')
            ch = getchar();
        _ = (ch != '0');
        return *this;
    }
    inline buf & operator >> (char & _) {
        return _ = char(getchar()), *this;
    }
    inline buf & operator >> (long & _) {
        ch = getchar();
        bol = false;
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        if(bol)
            _ = -_;
        return *this;
    }
    inline buf & operator >> (short & _) {
        ch = getchar();
        bol = false;
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        if(bol)
            _ = -_;
        return *this;
    }
    inline buf & operator >> (float & _) {
        ch = getchar();
        bol = false;
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar()) {
            _ = _ * 10 + ch - 48;
        }
        if(ch == '.') {
            ch = getchar();
            for(unsigned int cnt = 1; '0' <= ch && ch <= '9'; ch = getchar()) {
                cnt *= 10;
                _ += (ch - 48) * 1.0 / cnt;
            }
        }
        if(bol) {
            _ = -_;
        }
        return *this;
    }
    inline buf & operator >> (double & _) {
        ch = getchar();
        bol = false;
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar()) {
            _ = _ * 10 + ch - 48;
        }
        if(ch == '.') {
            ch = getchar();
            for(unsigned int cnt = 1; '0' <= ch && ch <= '9'; ch = getchar()) {
                cnt *= 10;
                _ += (ch - 48) * 1.0 / cnt;
            }
        }
        if(bol) {
            _ = -_;
        }
        return *this;
    }
    inline buf & operator >> (long long & _) {
        ch = getchar();
        bol = false;
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        if(bol)
            _ = -_;
        return *this;
    }
    inline buf & operator >> (long double & _) {
        ch = getchar();
        bol = false;
        if(ch == '-') {
            bol = true;
            ch = getchar();
        }
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar()) {
            _ = _ * 10 + ch - 48;
        }
        if(ch == '.') {
            ch = getchar();
            for(unsigned int cnt = 1; '0' <= ch && ch <= '9'; ch = getchar()) {
                cnt *= 10;
                _ += (ch - 48) * 1.0 / cnt;
            }
        }
        if(bol) {
            _ = -_;
        }
        return *this;
    }
    inline buf & operator >> (std::string & _) {
        std::getline(std::cin, _);
        return *this;
    }
    inline buf & operator >> (unsigned int & _) {
        ch = getchar();
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        return *this;
    }
    inline buf & operator >> (unsigned char & _) {
        return _ = getchar(), *this;
    }
    inline buf & operator >> (unsigned long & _) {
        ch = getchar();
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        return *this;
    }
    inline buf & operator >> (unsigned short & _) {
        ch = getchar();
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        return *this;
    }
    inline buf & operator >> (unsigned long long & _) {
        ch = getchar();
        while(ch == ' ' || ch == '\n' || ch == '\t')
            ch = getchar();
        for(_ = 0; '0' <= ch && ch <= '9'; ch = getchar())
            _ = _ * 10 + ch - 48;
        return *this;
    }

    template<typename type>
    inline buf & operator << (const type &val) {
        ios_base::sync_with_stdio(false);
        cout.tie(nullptr);
        return cout << val, *this;
    }
} co;

替罪羊树

C++
#pragma ScapegoatTree
#include <iostream>
#include <vector>

using std::vector;

struct Scapegoat {
    Scapegoat *left, *right;
    int key, size, cnt;
    bool deleted;
    bool needrebuild() const {
        return (*left).cnt > 0.7 * cnt + 5 || (*right).cnt > 0.7 * cnt + 5;
    }
    void maintain() {
        size = !deleted + (*left).size + (*right).size;
        cnt = 1 + (*left).cnt + (*right).cnt;
    }
} *null, *root;

inline void helprebuild(Scapegoat *o, vector <Scapegoat*> &v) {
    if (o == null)
        return;
    helprebuild((*o).left, v);
    if (!(*o).deleted)
        v.push_back(o);
    helprebuild((*o).right, v);
    if ((*o).deleted)
        delete o;
}

inline Scapegoat *build(vector <Scapegoat*> &v, int l, int r) {
    if (l >= r)
        return null;
    auto mid = (l + r) >> 1;
    Scapegoat *o = v[mid];
    (*o).left = build(v, l, mid);
    (*o).right = build(v, mid + 1, r);
    (*o).maintain();
    return o;
}

inline void rebuild(Scapegoat* &o) {
    vector <Scapegoat *> v;
    helprebuild(o, v);
    o = build(v, 0, v.size());
}

inline void insert(int x, Scapegoat* &o) {
    if (o == null) {
        o = new Scapegoat;
        (*o).left = (*o).right = null;
        (*o).deleted = false;
        (*o).size = (*o).cnt = 1;
        (*o).key = x;
        return;
    } else {
        ++o->size;
        ++o->cnt;
        (x >= (*o).key) ? insert(x, (*o).right) : insert(x, (*o).left);
        if ((*o).needrebuild()) {
            rebuild(o);
        }
    }
}

inline int rank(Scapegoat *now, int x) {
    auto ans = 1;
    while (now != null) {
        if ((*now).key >= x) {
            now = (*now).left;
        } else {
            ans += (*(*now).left).size + !(*now).deleted;
            now = (*now).right;
        }
    }
    return ans;
}

inline int numberth(Scapegoat *now, int x) {
    while (now != null) {
        if (!(*now).deleted && (*(*now).left).size + 1 == x)
            return (*now).key;
        if ((*(*now).left).size >= x) {
            now = (*now).left;
        } else {
            x -= (*(*now).left).size + !(*now).deleted;
            now = (*now).right;
        }
    }
}

inline void del(Scapegoat *o, int rank) {
    if (!(*o).deleted && rank == (*(*o).left).size + 1) {
        (*o).deleted = true;
        --o->size;
        return;
    }
    --o->size;
    (rank <= (*(*o).left).size + !(*o).deleted) ? del((*o).left, rank) : del((*o).right, rank - (*(*o).left).size - !(*o).deleted);
}

int main() {
    root = null = new Scapegoat;
    return 0;
}

质数判断

C++
inline bool IP(int n) {
    if (!n || n == 1) {
        return false;
    }
    for (int i = 2; i * i <= n; i++) {
        if (!(n % i)) {
            return false;
        }
    }
    return true;
}

红黑树

C++
#include <iostream>
#include <deque>

using namespace std;


const int MAX_N = 100010;

enum {RED, BLACK};

class rbTree {
public:
    class node {
    public:
        node *parent;
        node *child[2];
        int value, count, size, color;
    };

    node memoryPool[MAX_N];
    node *tail;
    node *delNodes[MAX_N];
    int delTop;

    node * newNode(int _value, int _color) {
        node *current;
        if (delTop) {
            current = delNodes[--delTop];
        } else {
            current = tail++;
        }
        // 原node的构造函数:
        current->value = _value;
        current->parent = current->child[0] = current->child[1] = nil;
        current->size = current->count = 1;
        current->color = _color;
        return current;
    }

    void deleteNode(node *current) {
        if (current == nil) {
            return;
        }
        delNodes[delTop++] = current;
    }

    node *root, *nil;

    rbTree() {
        tail = memoryPool;
        delTop = 0;

        nil = newNode(0, BLACK);
        nil->parent = nil->child[0] = nil->child[1] = nil;
        nil->count = nil->size = 0;

        root = nil;
    }

    void maintain(node *current) {
        if (current == nil) {
            return;
        }
        current->size = current->count + current->child[0]->size + current->child[1]->size;
    }

    int getType(node *current) { // 获得结点是左结点还是右结点,0左1右
        return current->parent->child[1] == current; // 父亲的右子结点 是不是 自己
    }

    int getType(node *parent, int value) {
        return value > parent->value;
    }

    void connect(node *parent, node *current, int type) { // 父结点指针,当前结点指针,类型(0左1右)
        parent->child[type] = current;
        current->parent = parent;
    }

    void DEBUGER(char fileName[], node *rt) { // 使用了splay part 2中的软件来绘图,调试神器
        FILE *fp = NULL;
        fp = fopen(fileName, "w");
        fprintf(fp, "digraph {\n");

        deque<node*> q; // 前序遍历,使用队列实现
        node *current;
        q.push_back(rt);
        while (!q.empty()) {
            current = q.front();
            q.pop_front();
            if (current == nil) {
                continue;
            }
            if (current->color == RED) {
                fprintf(fp, "\tn%d[label = \"%d\", fontcolor=white, style=filled, color=red]\n", current, current->value);
            } else {
                fprintf(fp, "\tn%d[label = \"%d\", fontcolor=white, style=filled, color=black]\n", current, current->value);
            }
            for (int i = 0; i < 2; ++i) {
                if (current->child[i] != nil) {
                    fprintf(fp, "\tn%d -> n%d[style = blod, taillabel = \"%d\"]\n", current, current->child[i], current->size);
                    q.push_back(current->child[i]);
                } else {
                    fprintf(fp, "\tnull%d%d[label = \"NULL\", style = dotted]\n", current, i);
                    fprintf(fp, "\tn%d -> null%d%d[style = dotted, taillabel = \"%d\"]\n", current, current, i, current->size);
                }
            }
        }
        fprintf(fp, "}");
        fclose(fp);
    }

    void rotate(node *parent, int type) { // type: 0左旋,1右旋
        if (parent == nil) {
            return;
        }

        node *current = parent->child[type ^ 1];
        if (current == nil) {
            return;
        }

        node *grandParent = parent->parent;
        int parentType = getType(parent);

        connect(parent, current->child[type], type ^ 1); // 将三角形结点挂到parent下
        connect(current, parent, type); // 儿子变爹,爹变儿子
        if (parent == root) {
            root = current;
        }
        connect(grandParent, current, parentType); // 爷爷承认新的子节点

        maintain(parent);
        maintain(current);
    }

    void updateSize(node *current) {
        while (current != nil) {
            maintain(current);
            current = current->parent;
        }
    }

    void insert(int value) {
        if (root == nil) {
            root = newNode(value, BLACK);
            return;
        }
        node *current = root;
        node *parent = current->parent;
        while (current != nil) { // 和查找一模一样
            current->size ++; // 提前更新
            if (current->value < value) {
                parent = current;
                current = current->child[1];
            } else if (current->value > value) {
                parent = current;
                current = current->child[0];
            } else { // 已经有相同结点了,将其count++即可。
                current->count ++;
                return;
            }
        }
        current = newNode(value, RED);
        connect(parent, current, getType(parent, value));
        insertFixup(current);
    }

    void insertFixup(node *current) {
        node *uncle;
        int parentType;
        while (current->parent->color == RED) {
            parentType = getType(current->parent);
            uncle = current->parent->parent->child[parentType ^ 1]; // 叔叔结点
            if (uncle->color == RED) { // case 1,见算法导论
                current->parent->color = BLACK;
                uncle->color = BLACK;
                current->parent->parent->color = RED;
                current = current->parent->parent;
            } else {
                if (getType(current) != parentType) {
                    current = current->parent;
                    rotate(current, parentType);
                }
                current->parent->color = BLACK;
                current->parent->parent->color = RED;
                rotate(current->parent->parent, parentType ^ 1);
            }
        }
        root->color = BLACK;
    }

    void transplant(node *u, node *v) {
        if (u == root) {
            root = v;
        }
        connect(u->parent, v, getType(u));
    }

    node * minimum(node *current) {
        while (current->child[0] != nil) {
            current = current->child[0];
        }
        return current;
    }

    void remove(node *z) { // 就是照着算法导论的伪代码打的
        if (z == nil) {
            return;
        }
        if (z->count > 1) {
            z->count --;
            updateSize(z);
            return;
        }
        node *x;
        node *y = z;
        int yOriginalColor = y->color;
        if (z->child[0] == nil) {
            x = z->child[1];
            transplant(z, z->child[1]);
        } else if (z->child[1] == nil) {
            x = z->child[0];
            transplant(z, z->child[0]);
        } else {
            y = minimum(z->child[1]);
            yOriginalColor = y->color;
            x = y->child[1];
            if (y->parent == z) {
                x->parent = y;
            } else {
                transplant(y, y->child[1]);
                connect(y, z->child[1], 1);
            }
            transplant(z, y);
            connect(y, z->child[0], 0);
            y->color = z->color;
        }
        updateSize(x->parent);
        if (yOriginalColor == BLACK) {
            removeFixup(x);
        }
        deleteNode(z);
    }

    void removeFixup(node *current) {
        node *brother;
        int type;
        while (current != root && current->color == BLACK)  {
            type = getType(current);
            brother = current->parent->child[type ^ 1];
            if (brother->color == RED) {
                brother->color = BLACK;
                current->parent->color = RED;
                rotate(current->parent, type);
                brother = current->parent->child[type ^ 1];
            }
            if (brother->child[0]->color == BLACK && brother->child[1]->color == BLACK) {
                brother->color = RED;
                current = current->parent;
            } else {
                if (brother->child[type ^ 1]->color == BLACK) {
                    brother->child[type]->color = BLACK;
                    brother->color = RED;
                    rotate(brother, type ^ 1);
                    brother = current->parent->child[type ^ 1];
                }
                brother->color = current->parent->color;
                current->parent->color = BLACK;
                brother->child[type ^ 1]->color = BLACK;
                rotate(current->parent, type);
                current = root;
            }
        }
        current->color = BLACK;
    }

    node* find(int value) {
        node *current = root; // 从根结点开始搜索
        while (current != nil) {
            if (current->value < value) {
                current = current->child[1]; // 小了,往大了走
            } else if (current->value > value) {
                current = current->child[0]; // 大了,往小了走
            } else { // 不大也不小不就是找到了吗?
                return current;
            }
        }
        return nil; // 找不到结点,退出。(找到得到结点的话会在while循环就退出)
    }

    int rankOfNode(int value) { // 即使查询的值不在树中,也能查。
        // 这里传入的value为被查询排名的结点的value
        node *current = root; // 从根结点开始搜索
        int leftSize = 1; // 左面的结点个数。提前将自己的大小1加上,你就想最左侧结点左面啥也没有但是排名为1
        while (current != nil) {
            if (current->value >= value) { // 玄学。即使找到了结点, 也还是会往左走到NULL结点后退出,走左子树不加,不影响结果。
                current = current->child[0];
            } else {
                leftSize += current->child[0]->size + current->count;
                current = current->child[1];
            }
        }
        return leftSize;
    }

    node* nodeOfRank(int rank) {
        node *current = root; // 从根结点查找
        while (current != nil) {
            if (rank > current->child[0]->size) {
                rank -= current->child[0]->size + current->count;
                if (rank <= 0) { // 减去了count,可能直接减出负数。如果减去左子树大小和当前结点大小之后为0或者负数,那么这个结点
                    return current;
                }
                current = current->child[1]; // 不是在左子树、当前结点,就是在右子树呗
            } else {
                current = current->child[0];
            }
        }
        return nil;
    }
};

int main()
{
    int n, opt, x;
    rbTree tree;

//    char debugStr[100];

    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
        scanf("%d%d", &opt, &x);

//        printf("%d %d %d:", i, opt, x);
//
//        if (i == 38) {
//            printf("aaa");
//        }

        switch (opt) {
            case 1: tree.insert(x); break;
            case 2: tree.remove(tree.find(x)); break;
            case 3: printf("%d\n", tree.rankOfNode(x)); break;
            case 4: printf("%d\n", tree.nodeOfRank(x)->value); break;
            case 5: printf("%d\n", tree.nodeOfRank(tree.rankOfNode(x) - 1)->value); break;
            case 6: printf("%d\n", tree.nodeOfRank(tree.rankOfNode(x + 1))->value); break;
        }

//        sprintf(debugStr, "./i%d_opt%d_x%d.dot", i, opt, x);
//        tree.DEBUGER(debugStr, tree.root);
    }
    return 0;
}

珂朵莉树

C++
class keduoli_tree {
  struct node {
    int l, r;
    mutable int val;
    inline bool operator<(const node& comp) const { return l < comp.l; }
  };

  set<node> s;

  inline void out() {
    for (node i : s)
      for (int j = i.l; j <= i.r; j++)
        printf("%d ", i.val);
    putchar('\n');
  }

  inline void insert(int l, int r = 0, int v = 0) { s.insert({l, r, v}); }

  inline set<node>::iterator split(int pos) {
    set<node>::iterator it = s.lower_bound({pos});
    if (it != s.end() && it->l == pos)
      return it;
    const int l = (--it)->l, r = it->r, v = it->val;
    s.erase(it);
    s.insert({l, pos - 1, v});
    return s.insert({pos, r, v}).first;
  }

  inline int sum(int l, int r) {
    int ret = 0;
    for (set<node>::iterator R = split(r + 1), L = split(l); L != R; L++)
      ret = (ret + (L->r - L->l + 1LL) * L->val) % 1000000007;
    return ret;
  }

  inline void assign(int l, int r, int val) {
    set<node>::iterator R = split(r + 1), L = split(l);
    s.erase(L, R);
    s.insert({l, r, val});
  }

  inline void add(int l, int r, int v) {
    for (set<node>::iterator R = split(r + 1), L = split(l); L != R; L++) {
      L->val += v;
      L->val += L->val >> 31 & 1000000007;
    }
  }

  inline void copy(int l1, int r1, int l2, int r2) {
    static vector<node> vec;
    vec.clear();
    for (set<node>::iterator R = split(r1 + 1), L = split(l1); L != R; L++)
      vec.push_back(*L);
    set<node>::iterator R = split(r2 + 1), L = split(l2);
    s.erase(L, R);
    for (node i : vec)
      s.insert({i.l - l1 + l2, i.r - l1 + l2, i.val});
  }

  inline void swap(int l1, int r1, int l2, int r2) {
    if (l1 > l2) {
      l1 ^= l2 ^= l1 ^= l2;
      r1 ^= r2 ^= r1 ^= r2;
    }
    static vector<node> v1, v2;
    v1.clear();
    v2.clear();
    for (set<node>::iterator R = split(r1 + 1), L = split(l1); L != R; ++L)
      v1.push_back(*L);
    for (set<node>::iterator R = split(r2 + 1), L = split(l2); L != R; ++L)
      v2.push_back(*L);
    set<node>::iterator R = split(r1 + 1), L = split(l1);
    s.erase(L, R);
    R = split(r2 + 1);
    L = split(l2);
    s.erase(L, R);
    for (node i : v1)
      insert(i.l - l1 + l2, i.r - l1 + l2, i.val);
    for (node i : v2)
      insert(i.l - l2 + l1, i.r - l2 + l1, i.val);
  }

  inline void reverse(int l, int r) {
    static vector<node> vec;
    vec.clear();
    for (set<node>::iterator R = split(r + 1), L = split(l); L != R; L++)
      vec.push_back(*L);
    set<node>::iterator R = split(r + 1), L = split(l);
    s.erase(L, R);
    for (node i : vec)
      s.insert({r - i.r + l, r - i.l + l, i.val});
  }
};