Graph偷懒 手打STL

· · 个人记录

上代码(class)

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,初始化

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

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

2.connect

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

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

4.begin,end,const_begin,const_end

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

5,.operator[]

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

Eg.

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的邻居