大眾 ID.BUZZ 內飾官圖公佈:定位純電 MPV,將於 3 月 10 日正式亮相
阿新 • • 發佈:2022-03-08
定義
#include <bits/stdc++.h> using namespace std; const int MAXN = 100+10; struct Edge { int from; int to; int length; Edge(int f,int t,int l):from(f),to(t),length(l){} bool operator< (Edge e) const { return length<e.length; } };
無向圖、有向圖的構造
vector<Edge> graph[MAXN];//無向圖 void NoDirectionInitial(int n) { //n條邊 int from,to,length; while (n--) { //n表示邊數 Edge p1(from,to,length); graph[from].push_back(p1); Edge p2(to,from,length); graph[to].push_back(p2); } } //有向圖 void DirectionInitial(int n) { //n條邊 int from,to,length;while (n--) { Edge p(from,to,length); graph[from].push_back(p); } }
並查集
int root[MAXN]; int height[MAXN]; //height只對根節點有意義,表示的是其子樹的最長長度(注意是“最長”) //初始化 void Initial(int n) { for (int i=0;i<n;i++) { root[i] = i; height[i] = 0; } } //查(查詢根節點),順便將其父節點直接指向其根節點int Find(int i) { if (i!=root[i]) { root[i] = Find(root[i]); } return root[i]; } //並(小樹並在大樹下) void Union(int x,int y) { x = Find(x); y = Find(y); if (x==y) { return ; } else { if (height[x]>height[y]) { root[y] = x; } else if (height[x]<height[y]){ root[x] = y; } else { root[x] = y; height[y]++; } } }
最小生成樹(Kruskal)(利用並查集)
priority_queue<Edge,vector<Edge>,greater<Edge>> edge; //構建小根堆,自動將第一個值為最小
int Kruskal(int n,int m) { //輸入n個頂點,m條邊,返回最小生成樹的權值 Initial(n); //初始化,讓每個點都各自為陣 int sum = 0; for (int i=0;i<m;i++) { Edge e = edge.top(); if (Find(e.from)!= Find(e.to)) { //如果首尾都還沒有連線過 Union(e.from,e.to); //就算是兩個獨立的結點,也能因為這條邊而使得根節點一樣了 sum += e.length; } edge.pop(); //如果處理完,或者首位已經在同一個樹中,則彈出,繼續處理下一個 } return sum; } int main() { int n,m; cin >> n >> m; for (int i=0;i<m;i++) { int from,to,length; cin >> from >> to >> length; Edge e(from,to,length); edge.push(e); } cout << Kruskal(n,m) << endl; return 0; }
最大連通數(利用並查集)
int ConnectGraph(int n) { int sum; for (int i=0;i<n;i++) { if (i==Find(i)) { //在此之前只有並操作,還沒有更新find操作 sum++; } } return sum; } int main() { int n,m; cin >> n >> m; Initial(n); for (int i=0;i<m;i++) { int from,to; cin >> from >> to; Union(from,to); } cout << ConnectGraph(n) << endl; return 0; }
DFS
BFS
DFS
------------恢復內容結束------------