跳到正文

个人记录

模板-缺省源

#SUSPENDED#约 21 分钟
原文

这是 2026年6月18日 存档的第 3 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年12月20日
收录
2026年6月16日
更新
2026年11月17日
篇幅
约 21 分钟
获赞
1

版本

  1. v4当前
  2. v3
  3. v2
  4. v1
算法模板

B3647 【模板】Floyd

AC记录

C++
// 邻接矩阵
for(int k=1;k<=n;k++){
  for(int i=1;i<=n;i++){
    for(int j=1;j<=n;j++){
      G[i][j]=min(G[i][j],G[i][k]+G[k][j]);
      G[j][i]=G[i][j];// 有向图删这行
    }
  }
}
P4779 【模板】单源最短路径(标准版)

AC记录
注意:这里可以使用dijkstra,但是mm离nn更近,所以选择堆优化的dijkstra,当然,SPFA也行。

C++
#include<bits/stdc++.h>
using namespace std;
const int INF=(1LL<<31)-1;
const int MAXN=1e5+5,MAXM=2e5+5;

struct edge{
    int v,w;
    edge(){}
    edge(int v_,int w_){ v=v_;w=w_; }
};

vector<edge> G[MAXN];

int* heap_dijkstra(const int& s,const int& count){ // 堆优化的dijkstra - O(n logm)
    struct Edge_Compare{ bool operator()(edge a,edge b){ return a.w>b.w; } };
    priority_queue<edge,vector<edge>,Edge_Compare> pq;
    int n=count+1;
    int *dis=new int[n+5];
    bool *vis=new bool[n+5];
    for(int i=0;i<=n;i++) dis[i]=INF;
    memset(vis,0,sizeof(bool)*n);
    dis[s]=0;
    pq.emplace(s,dis[s]);
    while(!pq.empty()){
        int cu=pq.top().v;
        int d=pq.top().w;
        pq.pop();
        if(vis[cu]) continue;
        vis[cu]=1;
        for(const auto& e:G[cu]){
            if(dis[e.v]>d+e.w){
                dis[e.v]=d+e.w;
                pq.emplace(e.v,dis[e.v]);
            }
        }
    }
    return dis;
}

本题弱化版:P3371 【模板】单源最短路径(弱化版)(这道题mm离n2n^2更近,所以选择朴素dijkstra)。

P10815 【模板】快速读入
C++
#include<cstdio>
inline long long read() {
    long long res = 0;
    char c = getchar();
    bool f = false;
    while (c == ' ' || c == '\n' || c == '\r' || c == '\t')
        c = getchar();
    if (c == '-') {
        f = true;
        c = getchar();
    }
    while (c >= '0' && c <= '9') {
        res = res * 10 + (c - '0');
        c = getchar();
    }
    return f ? -res : res;
}

教训
但该代码使用getchar单字符读入,每次读入都需要访问缓冲区,所以只能应付10610^6的数据。对于本题10810^8数据,需要采用以下fread一次性读入缓冲区方案。
AC记录

C++
// 缓冲区
const int BUF_SIZE = 1 << 25;
char buf[BUF_SIZE];
int p = 0, len = 0;

// 一次性填充缓冲区
inline char gc() {
    if (p == len) { // buf中还未读入数据
        len = fread(buf, 1, BUF_SIZE, stdin); // 从stdin一次性读入
        p = 0;
        if (!len) return EOF;
    }
    return buf[p++]; // 后续直接返回buf中的内容,不使用stdin
}

inline long long read() {
    long long res = 0;
    char c = gc();
    bool f = false;
    while (c < '0' || c > '9') {
        if (c == '-') f = true;
        c = gc();
    }
    while (c >= '0' && c <= '9') {
        res = res * 10 + (c ^ 48);
        c = gc();
    }
    return f ? -res : res;
}
__int128输出 / 快速输出
C++
inline void write(__int128_t n){ // 有符号__int128
    if(n < 0){
        putchar('-');
        n = -n;
    }
    if(n > 9) write(n / 10);
    putchar(n % 10 + '0');
}
inline void write(__uint128_t n){ // 无符号__int128
    if(n > 9) write(n / 10);
    putchar(n % 10 + '0');
}

需要注意的是,__int128类型是GCC扩展,在洛谷和NOI系列比赛中可用,但不保证部分OJ或环境(如MSVC)可用。对于C++原生类型,建议使用以下函数:

C++
#include <type_traits>
template<typename T>
inline void write(T x) {
    // 判断是否是无符号类型
    constexpr bool is_uns = std::is_unsigned_v<T>;
    if constexpr (!is_uns) {
        if (x < 0) {
            putchar('-');
            // 转无符号避免负数取模溢出
            x = -static_cast<std::make_unsigned_t<T>>(x);
        }
    }
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

迭代版防栈溢出:

C++
template<typename T>
inline void write(T x) {
    constexpr bool uns = std::is_unsigned_v<T>;
    if constexpr (!uns) {
        if (x < 0) {
            out_buf[out_p++] = '-';
            x = -static_cast<std::make_unsigned_t<T>>(x);
        }
    }
    int top = out_p;
    do {
        out_buf[out_p++] = (x % 10) + '0';
        x /= 10;
    } while (x);
    // 反转数字
    for (int l = top, r = out_p - 1; l < r; l++, r--)
        swap(out_buf[l], out_buf[r]);
}
// 批量刷新缓冲区
inline void flush() {
    fwrite(out_buf, 1, out_p, stdout);
    out_p = 0;
}

数据结构模板

注意

不要用STL!

B3614 【模板】栈

AC记录
C++类代码:

C++
template<typename _Tp=int>
class mystack{
private:
    _Tp *buf;
    unsigned long long ptr=0, ms;

public:
    mystack(long long size) : ms(size) {
        buf = new _Tp[ms];
    }
    
    ~mystack() { delete[] buf; }

    bool empty() const { return !ptr; }
    bool full() const { return ptr == ms; }

    int push(const _Tp& x) {
        if(full()) return -1;
        buf[ptr++] = x;
        return 0;
    }

    int pop() {
        if(empty()) return -1;
        ptr--;
        return 0;
    }

    _Tp top() const {
        return empty() ? _Tp(-1) : buf[ptr-1];
    }

    long long size() const { return ptr; }
    void clear() { ptr = 0; }

   
    mystack(const mystack&) = delete;
    mystack& operator=(const mystack&) = delete;
};

实践:

B3616 【模板】队列

AC记录
C++类代码:

C++
template<typename _Tp=int>
class myqueue{
private:
    _Tp *q;
    unsigned long long f=0, r=0, ms;

public:
    myqueue(long long size) : ms(size+1) {
        q = new _Tp[ms];
    }
    
    ~myqueue() { delete[] q; }

    bool empty() const { return f == r; }
    bool full() const { return (r+1)%ms == f; }

    int push(const _Tp& x) {
        if(full()) return -1;
        q[r] = x;
        r = (r+1)%ms;
        return 0;
    }

    int pop() {
        if(empty()) return -1;
        f = (f+1)%ms;
        return 0;
    }

    _Tp front() const {
        return empty() ? _Tp(-1) : q[f];
    }

    long long size() const {
        return (r - f + ms) % ms;
    }

    void clear() { f = r = 0; }

    myqueue(const myqueue&) = delete;
    myqueue& operator=(const myqueue&) = delete;
};
P3378 【模板】堆

AC记录
C++类代码:

C++
#include <stdexcept>
#include <algorithm>

template<typename T=int, typename Compare=std::greater<T>>
class myheap{
private:
    unsigned long long ms;
    T *p;
    unsigned long long len;
    Compare comp;

    bool valid(unsigned long long pos) const {
        return pos >= 1 && pos <= len;
    }

    // 二分查找插入位置
    unsigned long long findInsertPos(const T& val) const {
        if(len == 0) return 1;
        
        unsigned long long left = 1, right = len;
        while(left <= right) {
            unsigned long long mid = left + (right - left) / 2;
            if(!comp(p[mid], val) && (mid == 1 || comp(p[mid-1], val))) {
                return mid;
            } else if(comp(p[mid], val)) {
                left = mid + 1;
            } else {
                if(mid == 1) return 1;
                right = mid - 1;
            }
        }
        return left;
    }

    // 二分查找元素位置
    unsigned long long findElementPos(const T& val) const {
        unsigned long long left = 1, right = len;
        while(left <= right) {
            unsigned long long mid = left + (right - left) / 2;
            if(p[mid] == val) {
                // 找到最左边的相等元素
                while(mid > 1 && p[mid-1] == val) mid--;
                return mid;
            } else if(comp(val, p[mid])) {
                left = mid + 1;
            } else {
                if(mid == 1) return 0; // 不存在
                right = mid - 1;
            }
        }
        return 0; // 不存在
    }

public:
    myheap(unsigned long long size_max) : ms(size_max), len(0) {
        if(!size_max) throw std::invalid_argument("Max size can not be 0.");
        p = new T[ms + 1];
    }

    ~myheap() { delete[] p; }

    myheap(const myheap&) = delete;
    myheap& operator=(const myheap&) = delete;

    T get(unsigned long long pos) const {
        if(!valid(pos)) throw std::out_of_range("Access location does not exist.");
        return p[pos];
    }

    void modify(unsigned long long pos, const T& x) {
        if(!valid(pos)) throw std::out_of_range("Modify location does not exist.");
        erase(pos);
        push(x);
    }

    void erase(unsigned long long pos) {
        if(!valid(pos)) throw std::out_of_range("Delete location does not exist.");
        // 将后面元素前移
        for(unsigned long long i = pos; i < len; ++i) {
            p[i] = p[i+1];
        }
        len--;
    }

    void push(const T& val) {
        if(len >= ms) throw std::overflow_error("Heap is full, cannot insert.");
        
        // 找到插入位置并移动元素
        unsigned long long insertPos = findInsertPos(val);
        for(unsigned long long i = len; i >= insertPos; --i) {
            p[i+1] = p[i];
        }
        p[insertPos] = val;
        len++;
    }

    T top() const {
        if(!len) throw std::underflow_error("Heap is empty, no top.");
        return p[1];
    }
    
    void pop() {
        if(!len) throw std::underflow_error("Heap is empty, no top.");
        // 第一个元素后移
        for(unsigned long long i = 1; i < len; ++i) {
            p[i] = p[i+1];
        }
        len--;
    }
    
    bool empty() const { return len == 0; }
    bool full() const { return len >= ms; }
    unsigned long long size() const { return len; }
    void clear() { len = 0; }
    
    // 验证数组是否有序
    bool isOrdered() const {
        for(unsigned long long i = 1; i < len; ++i) {
            if(comp(p[i+1], p[i])) return false;
        }
        return true;
    }
};

练习:

U643423 【模板】动态大小数组

由于 U645395 【模板】动态大小数组(弱化版)是本题弱化版,所以本题类代码和该题通用。

C++类代码:

C++