算法学习——图论

拓扑排序(BFS的应用)

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>

using namespace std;

const int N = 1e5+10;
int h[N], e[N], ne[N], idx;
int n,m;
int d[N];
int ans[N],cnt;
void add(int a,int b)
{
    e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}

int topp()
{
    queue<int>q;
    for(int i=1;i<=n;i++)
    {
        if(d[i]==0)q.push(i);
    }
    while(!q.empty())
    {
        int t=q.front();q.pop();
        ans[cnt++]=t;
        
        for(int i=h[t];i!=-1;i=ne[i])
        {
            int j=e[i];
            d[j]--;//减边的操作
            if(d[j]==0)
            {
                q.push(j);
            }
        }
    }
    
    return cnt==n;
}

int main()
{
    memset(h, -1, sizeof h);
    cin>>n>>m;
    while (m -- )
    {
        int a,b;
        cin>>a>>b;
        add(a, b);
        d[b]++;
    }
    
    if(topp())
    {
        for(int i=0;i<cnt;i++)
        {
            cout<<ans[i]<<" ";
        }
    }
    else cout<<"-1"<<endl;
    
    return 0;
}

最短路

dijkstra算法

朴素版的

堆优化版的

#include <iostream>
#include <cstring>
#include <algorithm>
#include<queue>
using namespace std;

const int N = 1e6 + 10;
typedef pair<int, int> PII;

int h[N], e[N], ne[N],w[N], idx;
bool st[N];
int dist[N];
int n,m,s;
void add(int a, int b, int c)  // 添加一条边a->b,边权为c
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

void dijkstra()
{
    memset(dist,0x3f,sizeof dist);
    dist[s]=0;
     priority_queue<PII, vector<PII>, greater<PII> >heap;
    heap.push({0,s});//距离+编号
    
    while(heap.size())
    {
        PII t=heap.top();heap.pop();
        
        int id=t.second,distance=t.first;
        if(st[id])continue;
        st[id]=true;
        
        for(int i=h[id];i!=-1;i=ne[i])
        {
            int j=e[i];
            if(dist[j]>dist[id]+w[i])
            {
                dist[j]=dist[id]+w[i];
                heap.push({dist[j],j});
            }
        }
        
    }
    
}

int main()
{
    cin>>n>>m>>s;//n个点m条边
    memset(h,-1,sizeof h);
    
    while (m -- ){
        int a,b,c;
        cin>>a>>b>>c;
        add(a, b, c);
    }
    dijkstra();
    for(int i=1;i<=n;i++)
    {
    	cout<<dist[i]<<" ";
	}
    return 0;
}

[USACO09OCT] Heat Wave G - 洛谷

无向边的dijkstra只需要在建边的时候建两次就行

add(a, b, c);
add(b, a, c);

[USACO07NOV] Cow Hurdles S - 洛谷

试一下这个题能不能用dijkstra算法(堆优化+有向边(max和min))

SPFA

关于SPFA的经典好题 - 题单 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

模板

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

const int N=1e5+10;

#define fi first
#define se second

typedef pair<int,int> PII;//到源点的距离,下标号

int h[N],e[N],w[N],ne[N],idx=0;
int dist[N];//各点到源点的距离
bool st[N];
int n,m;
void add(int a,int b,int c){
    e[idx]=b;w[idx]=c;ne[idx]=h[a];h[a]=idx++;
}

int spfa(){
    memset(dist,0x3f,sizeof dist);
    dist[1]=0;
    queue<int>q;
    q.push(1);
    st[1]=true;//已经在队列里面了
    
    while(q.size())
    {
        int t=q.front();q.pop();
        st[t]=false;//出队列了
        
        for(int i=h[t];i!=-1;i=ne[i])
        {
            int j=e[i];
            if(dist[t]+w[i]<dist[j])
            {
                dist[j]=dist[t]+w[i];
                if(st[j]==0)
                {
                    q.push(j);
                    st[j]=true;//已经在队列里面了
                }
            }
        }
    }
    
    if(dist[n]==0x3f3f3f3f)return 0x3f3f3f3f;
    else return dist[n];
    
}

int main(){
    scanf("%d%d",&n,&m);
    memset(h,-1,sizeof h);
    while(m--){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    int res=spfa();
    if(res==0x3f3f3f3f) puts("impossible");
    else printf("%d",res);

    return 0;
}

如果要判断是否存咋负环,可以开一个数组cnt来记录边数,如果边数>=n的话,使用容斥原理可以知道存在负环。

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;

const int N=1e5+10;

#define fi first
#define se second

typedef pair<int,int> PII;//到源点的距离,下标号

int h[N],e[N],w[N],ne[N],idx=0;
int dist[N],cnt[N];//各点到源点的距离,加一个cnt记录所有遍历的边数,然后用容斥原理就可以判断是否有负环了
bool st[N];
int n,m;
void add(int a,int b,int c){
    e[idx]=b;w[idx]=c;ne[idx]=h[a];h[a]=idx++;
}

int spfa(){
    memset(dist,0x3f,sizeof dist);
    dist[1]=0;
    
    queue<int>q;
    for(int i=1;i<=n;i++)
    {
        st[i]=true;
        q.push(i);
    }
    
    while(q.size())
    {
        int t=q.front();q.pop();
        st[t]=false;//出队列了
        
        for(int i=h[t];i!=-1;i=ne[i])
        {
            int j=e[i];
            if(dist[t]+w[i]<dist[j])
            {
                dist[j]=dist[t]+w[i];
                cnt[j]=cnt[t]+1;
        
                if(cnt[j]>n)return true;
                if(st[j]==0)
                {
                    q.push(j);
                    st[j]=true;
                }
            }
        }
    }
    
    return false;
    
}

int main(){
    scanf("%d%d",&n,&m);
    memset(h,-1,sizeof h);
    while(m--){
        int a,b,c;
        scanf("%d%d%d",&a,&b,&c);
        add(a,b,c);
    }
    int res=spfa();
    if(res==1) puts("Yes");
    else printf("No");

    return 0;
}

Floyd

Floyd - 题单 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 210, INF = 1e9;

int n, m, Q;
int d[N][N];

void floyd()
{
    for (int k = 1; k <= n; k ++ )//k要放在最外层
        for (int i = 1; i <= n; i ++ )
            for (int j = 1; j <= n; j ++ )
                d[i][j] = min(d[i][j], d[i][k] + d[k][j]);// i j = i k k j
}

int main()
{
    scanf("%d%d%d", &n, &m, &Q);

    for (int i = 1; i <= n; i ++ )
        for (int j = 1; j <= n; j ++ )
            if (i == j) d[i][j] = 0;
            else d[i][j] = INF;

    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        d[a][b] = min(d[a][b], c);//有向图
    }
    floyd();
    while (Q -- )
    {
        int a, b;
        scanf("%d%d", &a, &b);

        int t = d[a][b];
        if (t > INF / 2) puts("impossible");
        else printf("%d\n", t);
    }

    return 0;
}

P2888 [USACO07NOV] Cow Hurdles S - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

这个题,稍微变了一下这个方程:d[i][j]=min(d[i][j],max(d[i][k],d[k][j]));

#include<bits/stdc++.h>
using namespace std;
const int N=310,INF=0x3f3f3f3f;
int n,m,T;
int d[N][N]; 
void floyd()
{
	for(int k=1;k<=n;k++)
	{
		for(int i=1;i<=n;i++)
		{
			for(int j=1;j<=n;j++)
			{
				d[i][j]=min(d[i][j],max(d[i][k],d[k][j]));
			}
		}
	}
}

int main()
{
	cin>>n>>m>>T;
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			if(i==j)d[i][j]=0;
			else d[i][j]=INF;
	
	while(m--)
	{
		int a,b,w;
		cin>>a>>b>>w;
		d[a][b]=min(d[a][b],w);
	}
	floyd();
	while(T--)
	{
		int a,b;
		cin>>a>>b;
		int dis=d[a][b];
		if(dis>INF/2)cout<<"-1"<<endl;
		else cout<<dis<<endl;
	}
	
	return 0;
}

 然后我发现23年蓝桥杯有一道题可以用Floyd的这个例题相同的思路来骗分(无向图,建边的时候建两次就行)

[蓝桥杯 2023 省 A] 网络稳定性 - 洛谷

看到题解里面说的:P3379 最近公共祖先【黄】+P3366 最小生成树【橙】=P9235 网络稳定性【蓝】,但是我还没学最近公共祖先

#include <cstring>
#include <iostream>
#include <algorithm>

using namespace std;

const int N = 510, INF = 1e9;

int n, m, Q;
int d[N][N];

void floyd()
{
    for (int k = 1; k <= n; k ++ )//k要放在最外层
        for (int i = 1; i <= n; i ++ )
            for (int j = 1; j <= n; j ++ )
                d[i][j] = max(d[i][j], min(d[i][k],d[k][j]));// i j = i k k j
}

int main()
{
    scanf("%d%d%d", &n, &m, &Q);
	//初始化 
    for (int i = 1; i <= n; i ++ )
        for (int j = 1; j <= n; j ++ )
           d[i][j] = -1;

    while (m -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        d[a][b] = max(d[a][b], c);
        d[b][a] = max(d[b][a], c);//无向 
    }
    floyd();
    while (Q -- )
    {
        int a, b;
        scanf("%d%d", &a, &b);

        int t = d[a][b];
        printf("%d\n", t);
    }

    return 0;
}

最小生成树

最小生成树算法及例题整理_求解最小生成树-CSDN博客

prim朴素版算法的模版

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 510,INF=0x3f3f3f3f;
int n,m;
int g[N][N];
int dist[N];
bool st[N];
int prim()
{
    memset(dist,0x3f,sizeof dist);
    
    int res=0;
    for(int i=0;i<n;i++)
    {
        int t=-1;
        for(int j=1;j<=n;j++)
        {
            //没有进入集合+距离比较小,更新
            if(!st[j]&&(t==-1||dist[j]<dist[t]))t=j;
        }
        
        //如果不连通,这个需要记一下,
        if(i&&dist[t]==INF)return INF;
        
        if(i)res+=dist[t];
        st[t]=true;
        
        for(int j=1;j<=n;j++)
        {
            dist[j]=min(dist[j],g[t][j]);//和最短路的区别就只是在这里
            //求解到集合的最短距离
        }
        
    }
    return res;
}


int main()
{
    scanf("%d%d", &n, &m);

    memset(g, 0x3f, sizeof g);

    while (m -- ){
        int a,b,c;
        scanf("%d%d%d", &a, &b,&c);
        g[a][b]=g[b][a]=min(g[a][b],c);
    }

    int t = prim();

    if (t == INF) puts("impossible");
    else printf("%d\n", t);

    return 0;
}

 Kruskal算法

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010, M = 200010, INF = 0x3f3f3f3f;
int n, m;
int p[N];

struct Edge
{
    int a,b,w;
    bool operator <(const Edge &W)const
    {
        return w<W.w;
    }
}edges[M];

int find(int x)
{
    if(p[x]!=x)p[x]=find(p[x]);
    return p[x];
}

int kruskal()
{
    sort(edges,edges+m);
    for(int i=1;i<=n;i++)p[i]=i;
    
    int res=0;//记录权重之和
    int cnt=0;//记录边数
    
    for(int i=0;i<m;i++)
    {
        int a=edges[i].a,b=edges[i].b,w=edges[i].w;
        a=find(a),b=find(b);
        if(a!=b)//使用并查集进行查询
        {
            p[a]=b;
            res+=w;
            cnt++;
        }
    }
    
    if(cnt<n-1)return INF;
    else return res;
   
}



// int kruskal()
// {
//     sort(edges,edges+m);
    
//     for(int i=1;i<=n;i++)p[i]=i;
    
//     int res=0,cnt=0;
//     for(int i=0;i<m;i++)
//     {
//         int a=edges[i].a,b=edges[i].b,w=edges[i].w;
        
//         a=find(a),b=find(b);
//         if(a!=b)
//         {
//             p[a]=b;//合并
//             res+=w;
//             cnt++;
//         }
//     }
//     if(cnt<n-1)return INF;
//     return res;
// }


int main()
{
    scanf("%d%d", &n, &m);

    for (int i = 0; i < m; i ++ )
    {
        int a, b, w;
        scanf("%d%d%d", &a, &b, &w);
        edges[i] = {a, b, w};
    }

    int t = kruskal();

    if (t == INF) puts("impossible");
    else printf("%d\n", t);
    
    return 0;
}

最近公共祖先

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值