2025清北学堂寒假 CSP-S NOIP 储备营 Day6(1.27) 最小生成树、拓扑排序、图的联通性问题;数论:Lcm、gcd、高精度、进制转换、同余基础、计数问题、欧几里得、素数筛法、素数性质

· · 个人记录

授课老师:钟皓曦

清华姚班 NOI2013 金牌

注:本文章中添加 \color{red} \bullet 的笔记内容是难点,需要仔细理解。

图论

最小生成树-Kruskal

对于 \texttt{Prim} 算法,它死了,暂且不管它。

洛谷原题见 \texttt{P3366 【模板】最小生成树}。

\color{red} \texttt{Code:}
#include<bits/stdc++.h>
using namespace std;
struct node{
    int pa,pb,d;
} e[200005];
bool cmp(node a,node b){
    return a.d<b.d;
}
/*bool operator<(const node &a,const node &b){
    return a.d<b.d;
} */
int fath[200005],fa,fb,n,m,ans,cntedge;
int find(int x){
    if(x==fath[x]){
        return x;
    }
    else{
        return fath[x]=find(fath[x]);
    }
}
int main(){
    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;i++){
        scanf("%d %d %d",&e[i].pa,&e[i].pb,&e[i].d);
    }
    sort(e+1,e+m+1,cmp);
    for(int i=1;i<=n;i++){
        fath[i]=i;
    }
    for(int i=1;i<=m;i++){
        fa=find(e[i].pa);
        fb=find(e[i].pb);
        if(fa!=fb){
            cntedge++;
            ans+=e[i].d;
            fath[fa]=fb;
        }
    }
    if(cntedge<=n-2){ //总共有 n-1 条边,如果小于 n-1,说明不连通 
        printf("orz\n");
    }
    else{
        printf("%d\n",ans);
    }
    return 0;
} 

例题

1. \texttt{HDU-4786 Fibonacci Tree}

强连通分量

有向图中,点之间能够互相走到,则被称为强连通分量,特别地,一个点本身也可以是强连通分量。

\color{red} \texttt{Code:}
#include<bits/stdc++.h>

using namespace std;
const int maxn=100010;
int n,m;
vector<int> z[maxn];
int t;//当前dfs了几个点 
int dfn[maxn];//dfn[i] 代表i点是第几个被dfs到的
int low[maxn];
//low[i] 从i出发 可以走 树边、回边、能扩大环的横叉边 走到的所有点中 dfn最小是多少 
stack<int> st;//用来存 还没有被求出强连通分量的点 
bool instack[maxn];//instack[i] i点是否在栈里面
int cnt;//代表有多少个强连通分量
int belong[maxn];//belong[i] 第i个点属于第几个强连通分量 
void dfs(int i)//深搜i点
{
    t++;dfn[i] = low[i] = t;
    st.push(i);instack[i] = true;
    for (auto j : z[i])//枚举从i出发的所有边
        if (dfn[j] == 0) //树边
        {
            dfs(j);
            low[i] = min(low[i],low[j]);
        }
        else //回边 或者 横叉边 
        {
            if (instack[j]) low[i]=min(low[i],dfn[j]);
            //if (instack[j]) low[i]=min(low[i],low[j]);
        }
    if (dfn[i] == low[i])//i点是他所属的强连通分量最上面的点 
    {//把i所属的强连通分量处理出来 
        cnt ++;
        while (st.top() != i)
        {
            belong[st.top()] = cnt;
            instack[st.top()] = false;
            st.pop();
        }
        st.pop();
        instack[i]=false;
        belong[i]=cnt;
    }
} 

int main()
{
    cin >> n >> m;
    for (int i=1;i<=m;i++)
    {
        int p1,p2;
        cin >> p1 >> p2;
        z[p1].push_back(p2);
    }
    for (int i=1;i<=n;i++)
        if  (dfn[i]==0) dfs(i);

    return 0;
}

2-SAT 问题

例题

1. \texttt{P4782 【模板】2-SAT}

2. \texttt{UVA1514 Piece it together}

数论

最大公约数(欧几里得,gcd)和拓展欧几里得(exgcd)

例题

1. \texttt{P5656 【模板】二元一次不定方程 (exgcd)}

2. \texttt{P1082 [NOIP2012 提高组] 同余方程}

后记

更多题目详细内容,请跳转至 \texttt{2025清北学堂寒假提高组储备营Day6题单}。

更多内容,请移步至 \color{red}\texttt{ryf2011}。