圖論概論

什麼是圖?

名詞介紹

*節點(node)

*邊(edge)

*度數(degree)

*樹圖(tree)

*父節點(parent)

*子節點(child)

*DAG

如何存圖?

相鄰矩陣

1 2 3 4 5 6 7
1 0 1 1 0 0 1 1
2 1 0 1 0 0 0 0
3 1 1 0 0 0 1 0
4 0 0 0 0 0 1 0
5 0 0 0 0 0 1 0
6 1 0 1 1 1 0 0
7 1 0 0 0 0 0 0

空間不夠(?

相鄰節點vector

1: 2,3,6,7

2: 1,3

3: 1,2,6

4: 6

5: 6

6: 1,3,4,5

7: 1

example code

int n,m;
vector<int> mapa[100010];

cin>>n>>m;
int a,b;
for (int i=0;i<m;i++){
  cin>>a>>b;
  mapa[a].push_back(b);
  mapa[b].push_back(a);
}
int n,m;
int mapa[1010][1010];

cin>>n>>m;
int a,b;
for (int i=0;i<m;i++){
  cin>>a>>b;
  mapa[a][b]=1;
  mapa[b][a]=1;
}

經典算法:DFS

#include<bits/stdc++.h>
using namespace std;

int n,m;
vector<int> mapa[100010];
int vis[100010];
void DFS(int I){
	vis[I]=1;
	cout<<I<<' ';
	for (int x:mapa[I]){
		if (!vis[x]){
			DFS(x);
		}
	}
}
int main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n>>m;
	int a,b;
	for (int i=0;i<m;i++){
		cin>>a>>b;
		mapa[a].push_back(b);
		mapa[b].push_back(a);
	}
	DFS(1);
	return 0;
}

經典算法:BFS

#include<bits/stdc++.h>
using namespace std;

int n,m;
vector<int> mapa[100010];
int vis[100010];
queue<int> Q;
void BFS(){
	int from;
	Q.push(1);
	vis[1]=1;
	while (Q.size()){
		from=Q.front();Q.pop();
		cout<<from<<' ';
		for (int x:mapa[from]){
			if (!vis[x]){
				Q.push(x);
				vis[x]=1;
			}
		}
	}
}
int main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	cin>>n>>m;
	int a,b;
	for (int i=0;i<m;i++){
		cin>>a>>b;
		mapa[a].push_back(b);
		mapa[b].push_back(a);
	}
	BFS();
	return 0;
}
#include<bits/stdc++.h>
using namespace std;

int n,m,ans;
vector<int> mapa[100010];
int color[100010];
void DFS(int I,int source){
	color[I]=!color[source];
	for (auto x:mapa[I]){
		if (color[x]==-1){
			DFS(x,I);
		}else {
			if (color[x]==color[I]){
				ans=0;
			}
		}
	}
}
int main(){
	ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	while (cin>>n&&n){
		ans=1;
		for (int i=0;i<n;i++){
			mapa[i].clear();
			color[i]=-1;
		}
		cin>>m;
		int a,b;
		for (int i=0;i<m;i++){
			cin>>a>>b;
			mapa[a].push_back(b);
			mapa[b].push_back(a);
		}
		color[0]=0;
		DFS(0,-1);
		if (ans){
			cout<<"NOT BICOLORABLE.\n";
		}else {
			cout<<"BICOLORABLE.\n";
		}
	}
	return 0;
}

圖論概論

By jeffreylin0909

圖論概論

  • 163