【模板】邻接矩阵

邻接矩阵模板

  • 存储
    • 给出矩阵
    • 给出连边
  • 遍历
    • dfs
    • bfs
  • 最短路
    • Floyd
    • Dijkstra
  • 最小生成树
    • Prim

存储

#include
#define size 10001
using namespace std;
int n, g[size][size];

给出矩阵

inline void input()
{
	scanf( "%d", &n);
	for ( int i = 1; i <= n; i++ )
	for ( int j = 1; j <= n; j++ )
	scanf( "%d", &g[i][j] );
}

给出连边

inline void input()
{
	scanf( "%d", &n);
	for ( int u, v, t, i = 1; i <= n; i++ )
	{
		scanf( "%d %d %d", &u, &v, &t );
		g[u][v] = t;
		g[v][u] = t; // 无向图
	}
}

遍历

dfs

bool vis[size];
inline void dfs( int x )
{
	for ( int i = 1; i <= n; i++ )
	if ( g[x][i] )
	if ( !vis[i] )
	{
		vis[i] = true;
		dfs( i );
	}
}

bfs

queue < int > q;
bool vis[size];
inline void bfs( int r )
{
	for ( q.push( r ), vis[r] = true; !q.empty();  )
	{
		int x = q.front();
		q.pop();
		for ( int i = 1; i <= n; i++ )
		if ( g[x][i] )
		if ( !vis[i] )
		{
			vis[i] = true;
			q.push( i );
		}
	}
}

最短路

Floyd

int dis[size][size], path[size][size];
inline void Floyd()
{
	memset( dis, 0x3f, sizeof ( dis ) );
	for ( int i = 1; i <= n; i++ )
	for ( int j = 1; j <= n; j++ )
	dis[i][j] = g[i][j];
	for ( int k = 1; k <= n; k++ )
	for ( int i = 1; i <= n; i++ )
	for ( int j = 1; j <= n; j++ )
	if ( dis[i][k]+dis[k][j] < dis[i][j] )
	{
		dis[i][j] = dis[i][k]+dis[k][j];
		path[i][j] = k; // 中转点
	}
}

Dijkstra

int dis[size];
bool vis[size];
inline void Dijkstra( int s )
{
	memset( dis, 0x3f, sizeof( dis ) );
	dis[s] = 0;
	memset( vis, false, sizeof( vis ) );
	for ( int Min, u, i = 1; i <= n; i++ )
	{
		Min = 0x7fffffff;
		for ( int j = 1; j <= n; j++ )
		if ( !vis[i] && dis[j] < Min )
		{
			Min = dis[j];
			u = j;
		}
		vis[u] = true;
		for ( int j = 1; j <= n; j++ )
		if ( g[u][j] && dis[u]+g[u][j] < dis[j] )
		{
			dis[j] = dis[u]+g[u][j];
		}
	}
}

最小生成树

Prim

int dis[size], siz;
bool vis[size];
inline void Prim( int s )
{
	memset( dis, 0x3f, sizeof( dis ) );
	dis[s] = 0;
	memset( vis, false, sizeof( vis ) );
	for ( int Min, u, i = 1; i <= n; i++ )
	{
		Min = 0x7fffffff;
		for ( int j = 1; j <= n; j++ )
		if ( !vis[j] && dis[j] < Min )
		{
			Min = dis[j];
			u = j;
		}
		vis[u] = true;
		for ( int j = 1; j <= n; j++ )
		if ( !vis[j] && g[u][j] < dis[j] )
		{
			dis[j] = g[u][j];
		}
	}
	for ( int i = 1; i <= n; i++ ) siz += dis[i];
}

你可能感兴趣的:(【模板】)