Created
April 9, 2017 13:44
-
-
Save creatorlxd/05de175c6f234cd13cfb373c76b84388 to your computer and use it in GitHub Desktop.
一个通用的图类
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
#include <stack> | |
using namespace std; | |
struct Edge | |
{ | |
int Start = -1; | |
int End = -1; | |
int K = 0; | |
Edge(int s, int e) :Start(s), End(e),K(0) {} | |
Edge(int s, int e,int k) :Start(s), End(e),K(k) {} | |
}; | |
bool operator < (const Edge& e1, const Edge& e2) | |
{ | |
return (e1.Start == e2.Start ? e1.End < e2.End : e1.Start < e2.Start); | |
} | |
class Graph | |
{ | |
protected: | |
int m_EdgesNumber; | |
int m_NodesNumber; | |
vector<Edge> m_Edges; | |
vector<int> m_NodesHead; | |
public: | |
Graph() | |
{ | |
m_EdgesNumber = 0; | |
m_NodesNumber = 0; | |
} | |
void InitEdges() | |
{ | |
for (int i = 0; i < m_EdgesNumber; i++) | |
{ | |
m_Edges.push_back(Edge(-1,-1)); | |
} | |
} | |
void InitNodesHead() | |
{ | |
for (int i = 0; i < m_NodesNumber; i++) | |
{ | |
m_NodesHead.push_back(m_NodesNumber); | |
} | |
int buff = -1; | |
for (size_t i=0;i<m_Edges.size();i++) | |
{ | |
if (m_Edges[i].Start != buff) | |
{ | |
buff = m_Edges[i].Start; | |
m_NodesHead[buff] = i; | |
} | |
} | |
} | |
int GetNodesEdgesNumber(int node) | |
{ | |
if (m_NodesHead[node] == -1) | |
return 0; | |
else | |
{ | |
if (node == m_NodesNumber - 1) | |
{ | |
return (m_NodesNumber - m_NodesHead[node]); | |
} | |
else | |
{ | |
return (m_NodesHead[node + 1] - m_NodesHead[node]); | |
} | |
} | |
} | |
vector<int> GetNodesEdges(int node) | |
{ | |
int head = m_NodesHead[node]; | |
if (head == -1) | |
return vector<int>(); | |
else | |
{ | |
int size = GetNodesEdgesNumber(node); | |
if (size == 0) | |
{ | |
return vector<int>(); | |
} | |
else | |
{ | |
vector<int> re; | |
for (int i = m_NodesHead[node]; i < m_NodesHead[node] + size; i++) | |
{ | |
re.push_back(m_Edges[i].End); | |
} | |
return re; | |
} | |
} | |
} | |
int GetNodesK(int from, int to) | |
{ | |
int head = m_NodesHead[from]; | |
if (head == -1) | |
return -1; | |
else | |
{ | |
for (int i = head; i < head + GetNodesEdgesNumber(from); i++) | |
{ | |
if (m_Edges[i].End == to) | |
return m_Edges[i].K; | |
} | |
return -1; | |
} | |
} | |
virtual void Read() | |
{ | |
cin >> m_NodesNumber >> m_EdgesNumber; | |
InitEdges(); | |
for (Edge& i : m_Edges) | |
{ | |
// cin >> i.Start >> i.End>>i.K; | |
cin >> i.Start >> i.End; | |
} | |
sort(m_Edges.begin(), m_Edges.end()); | |
InitNodesHead(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment