Skip to content

Commit 4e91cb1

Browse files
committed
Prim with adjacency list
1 parent 5a06b82 commit 4e91cb1

File tree

2 files changed

+76
-6
lines changed

2 files changed

+76
-6
lines changed

graph_theory.tex

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
\chapter{图论}
55
\label{graph_theory}
66

7-
7+
\newcommand{\prefixgrapthy}[1]{graph\_theory/#1}
8+
\newcommand{\xprefixgrapthy}[1]{graph_theory/#1}
89

910
\section{最短路}
1011

@@ -44,12 +45,21 @@ \subsection{Floyd,邻接矩阵存储}
4445

4546

4647
\section{最小生成树 / 森林}
47-
\subsection{Prim}
48-
例:\href{https://xoj.red/problems/show/1240}{XOJ 1240 Agri-Net 最短网络}
49-
\lstinputlisting{graph_theory/mst_prim_matrix.cpp}
5048

51-
\subsection{Prim + priority\_queue优化}
52-
\lstinputlisting{graph_theory/mst_prim_priority_queue.cpp}
49+
\begin{example}[最小生成树]
50+
\href{https://xoj.red/problems/show/1240}{XOJ 1240 Agri-Net 最短网络}
51+
\end{example}
52+
53+
\xsubsection{Prim + 邻接矩阵}{\prefixgrapthy{mst\_prim\_matrix.cpp}}
54+
55+
\lstinputlisting{\xprefixgrapthy{mst_prim_matrix.cpp}}
56+
57+
\xsubsection{Prim + 邻接表}{\prefixgrapthy{mst\_prim\_vector.cpp}}
58+
59+
\lstinputlisting{\xprefixgrapthy{mst_prim_vector.cpp}}
60+
61+
\xsubsection{Prim + priority\_queue优化}{\prefixgrapthy{mst\_prim\_priority\_queue.cpp}}
62+
\lstinputlisting{\xprefixgrapthy{mst_prim_priority_queue.cpp}}
5363

5464
\subsection{Kruskal}
5565
\lstinputlisting{graph_theory/mst_kruskal.cpp}

graph_theory/mst_prim_vector.cpp

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
const int maxn = 110, INF = 0x3fffffff;
4+
struct Edge {
5+
int from, to, dist;
6+
Edge(int u, int v, int w):from(u),to(v),dist(w){}
7+
};
8+
struct Prim {
9+
int n, m;
10+
vector<Edge> edges;
11+
vector<int> G[maxn]; //G[i]表示从顶点i出发的所有边的编号
12+
bool vis[maxn];
13+
14+
void init(int n) {
15+
this->n = n;
16+
for (int i=0; i<n; i++) G[i].clear();
17+
edges.clear();
18+
}
19+
20+
void add_edge(int from, int to, int dist) {
21+
edges.push_back(Edge(from, to, dist));
22+
m = edges.size();
23+
G[from].push_back(m-1);
24+
}
25+
26+
int prim(int u) {
27+
int ans = 0;
28+
vis[u] = true;
29+
for (int i=0; i<n-1; i++) {
30+
int min = INF, sel_e;
31+
for (int j=0; j<n; j++) {
32+
if (!vis[j]) continue;
33+
for (int k=0; k<G[j].size(); k++) {
34+
Edge &e = edges[G[j][k]];
35+
if (!vis[e.to] && e.dist<min) {
36+
min = e.dist;
37+
sel_e = G[j][k];
38+
}
39+
}
40+
}
41+
Edge &e = edges[sel_e];
42+
vis[e.to] = true;
43+
ans += e.dist;
44+
}
45+
return ans;
46+
}
47+
} mst;
48+
49+
int main() {
50+
int n, w;
51+
scanf("%d", &n);
52+
mst.init(n);
53+
for (int i=0; i<n; i++)
54+
for (int j=0; j<n; j++) {
55+
scanf("%d", &w);
56+
if (i != j)
57+
mst.add_edge(i, j, w); //邻接矩阵自动会加反向边
58+
}
59+
printf("%d\n", mst.prim(0));
60+
}

0 commit comments

Comments
 (0)