跳到正文

个人记录

Graph偷懒 手打STL

__yyx__约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年7月31日
收录
2025年12月12日
更新
2026年10月28日
篇幅
约 4 分钟

版本

  1. v2当前
  2. v1

上代码(class)

C++
template<typename t>
class graph{
public:
	vector<vector<pair<int , t>>> adj;
	int siz;
	graph(){}
	graph(int n): adj(vector<vector<pair<int , t>>>(n)) , siz(n) {}
	void resize(int n){
		siz = n;
		adj.resize(n);
	}
	size_t capacity(){
		return siz;
	}
	size_t size(){
		return siz;
	}
	void connect(int a , int b , t wgt = 1 , bool dir = false , bool del = true){
		bool f = false;
		if(del){
			for(auto& i : adj[a]){
				if(i.first == b){
					f = true;
					i.second = min(i.second , wgt);
				}
			}
		}
		if(!f){
			adj[a].push_back({b , wgt});
		}
		if(!dir){
			if(del){
				for(auto& i : adj[b]){
					if(i.first == a){
						f = true;
						i.second = min(i.second , wgt);
					}
				}
			}
			if(!f){
				adj[b].push_back({a , wgt});
			}
		}
	}
	bool count(int a , int b){
		for(auto i : adj[a]){
			if(i.first == b)return 1;
		}
		return 0;
	}
	auto& operator[](const int n){
		return adj[n];
	}
	typename vector<vector<pair<int , t>>> :: iterator begin(){
		return adj.begin();
	}
	typename vector<vector<pair<int , t>>> :: iterator end(){
		return adj.end();
	}
	typename vector<vector<pair<int , t>>> :: const_iterator const_begin(){
		return adj.begin();
	}
	typename vector<vector<pair<int , t>>> :: const_iterator const_end(){
		return adj.end();
	}
};

用法

1.resize,初始化

C++
graph<typename> g; //定义边权类型为typename的图
graph<typename> g(5); //定义边权类型为typename, 大小为5(点编号0-4)的图

g.resize(5); // 让g大小为5(点编号0-4)

2.connect

C++
g.connect(a , b); //建一条a->b的无向边(边权1)
g.connect(a , b , t); //建一条a->b的无向边(边权t)
g.connect(a , b , t , true); //建一条a->b的有向边(边权t)
g.connect(a , b , t , true , false); ////建一条a->b的有向边(边权t),保留重边

3.size,capacity

C++
unsigned long long i = g.size(); //同capacity,返回大小

4.begin,end,const_begin,const_end

C++
g.begin() ; //返回g的邻接表begin,end,及其常量指针

5,.operator[]

C++
g[1] // 一个vector<pair<int , t>>,first为1的邻居节点,second为1到1的邻居节点的边权。

Eg.

C++
graph<double> g(n + 1);
for(int i = 1 ; i <= n ; i ++){
  int a , b;
  cin >> a >> b;
  g.connect(a , b);
}
for(auto i : g[1]){
  cout << i.first << "\n";
}

功能:输出1的邻居

原文