4 solutions

  • 3
    @ 2025-3-30 14:47:43

    floyd 魔改

    • 1
      @ 2025-3-29 22:22:39

      floyd

      • 1
        @ 2025-3-29 12:00:32

        最短路算法 设f[a][b]表示岛a岛b之间的最短路,一开始初始化为∞ 对于询问0 a b,如果f[a][b]== ∞,则输出-1,否则输出f[a][b]

        • 0
          @ 2025-4-2 21:57:18

          看被人都是用Floyd写的,我要写一篇独一无二的题解

          题目传送门

          首先每次有一组询问,每一行的第一个数(称他为opt吧!)如果他为0,那就查询无向图里a和b是否联通
          否则,就新增一条航线!(注意,这个航线是双向的,所以要开两倍的空间)
          用静态邻接表(链式前向星)或vector
          这里,我用的是vector
          上代码!(freopen被我吃了)
          #include <bits/stdc++.h>
          using namespace std;
          const int MAXH = 2002;
          int n,m;
          struct edge{
          	int v,w;
          };
          vector <edge> e[2002];
          void add(int a,int b,int s){
          	e[a].push_back((edge){b,s});
          	e[b].push_back((edge){a,s});
          }
          struct node{
          	int dis,u;
          	bool operator > (const node &a) const{
          		return dis > a.dis;
          	}
          };
          priority_queue<node,vector<node>,greater<node>>q;
          int dis[MAXH];
          bool vis[MAXH];
          void dijkstra(int s){
          	memset(dis, 0x3f3f3f3f, sizeof(dis));
          	memset(vis, false, sizeof(vis));
          	dis[s] = 0;
          	q.push({0,s});
          	while(!q.empty()){
          		int u = q.top().u;
          		q.pop();
          		if(vis[u]){
          			continue;
          		}
          		vis[u] = 1;
          		for(auto ed : e[u]){
          			int v = ed.v,w = ed.w;
          			if(dis[v] > dis[u] + w){
          				dis[v] = dis[u] + w;
          				q.push({dis[v],v});
          			}
          		}
          	}
          }
          int main()
          {
          //	freopen("trip.in","r",stdin);
          //	freopen("trip.out","w",stdout); 
          	scanf("%d%d",&n,&m);
          	for(int i = 1;i <= m;i++){
          		int opt,a,b;
          		scanf("%d%d%d",&opt,&a,&b);
          		if(opt == 1){
          			int e;
          			scanf("%d",&e);
          			add(a,b,e);
          		}else{
          			dijkstra(a);
          			if(dis[b] != 0x3f3f3f3f){
          				printf("%d\n",dis[b]);
          			}else{
          				printf("-1\n");
          			}
          			
          		}
          	}
          	return 0; //完美收工
          }
          
          该代码使用 Dijkstra 算法来查找图中的最短路径。Dijkstra 算法的时间复杂度为 O((V+E)logV),其中 V 是顶点数,E 是边数。在这种情况下,n 表示顶点数,m 表示边数。因此,总体时间复杂度为 O((n+m)logn)

          AC!

          • 1

          Information

          ID
          4
          Time
          1000ms
          Memory
          128MiB
          Difficulty
          5
          Tags
          # Submissions
          16
          Accepted
          6
          Uploaded By