尼瑪啊,C++的哈希真是難用到爆,我還非常執拗的不想用boost,結果發現也沒啥差,functional的hash函數效果一樣。
代碼沒有驗證,但是問題不大
#include<iostream>
#include<vector>
#include<list>
#include<unordered_map>
#include<unordered_set>
#include <string>
#include<functional>
#include<string.h>
using namespace std;
class Edge;
class Node ///<節點
{
public:
int value;//權值
int in;//入度
int out;//出度
list<Edge> edge;//出的邊
list<Node> nextnode;//出的邊連的節點
Node(int valuee)
{
value = valuee;
in = 0;
out = 0;
}
};
class Edge ///<邊
{
public:
int weight;//權重
Node *from;//有向圖的起點
Node *to;//有向圖的終點
int num;
Edge(int weightt, Node *fromm, Node *too)
{
weight = weightt;
from = fromm;
to = too;
num = -1;
}
};
struct func //hash 函數
{
size_t operator()(const Edge a) const
{
return ((hash<int>()(a.weight)
^ (hash<Node*>()(a.from) << 1)) >> 1)
^ (hash<Node*>()(a.to) << 1);
}
};
struct cmp_fun //比較函數 ==
{
bool operator()(const Edge &a, const Edge &b) const
{
return memcmp(&a, &b, sizeof(a)) == 0 ? true:false;
}
};
class Graph//完整的圖結構
{
public:
unordered_map<int, Node>node;
unordered_set<Edge, func,cmp_fun>edge;
};
Graph graph;
void ReadGraph(vector<vector<int>>a)//讀圖程序
{
int n = a.size();
for (int i = 0; i<n; ++i)
{
int weight = a[i][0];
int from = a[i][1];
int to = a[i][2];
///<下面兩行代碼過後不管from和to是否出現過就都有了
if (graph.node.find(from) == graph.node.end())//如果from點從沒在哈希中出現過就加入
graph.node.insert(pair<int, Node>(from, Node(from)));
if (graph.node.find(to) == graph.node.end())//如果to點從沒在哈希中出現過就加入
graph.node.insert(pair<int, Node>(to, Node(to)));
Node* p_fromNode = &graph.node.find(from)->second;//在哈希表中提出from點
Node* p_toNode = &graph.node.find(to)->second;//提出to點
p_fromNode->nextnode.push_back(*p_toNode);//from節點的next節點是to
++p_fromNode->out;//from的出度++
++p_toNode->in;//to節點的入度++
Edge newedge = Edge(weight, p_fromNode, p_toNode);//建立一條邊
p_fromNode->edge.push_back(newedge);//把這條邊加入到from點的邊集中
graph.edge.insert(newedge);//把這條邊加入到圖中
}
}
int main(void)
{
vector<vector<int>>a;
for (int i = 0; i<8; ++i)
{
vector<int>temp;
for (int j = 0; j<3; ++j)
{
int xx;
cin >> xx;
temp.push_back(xx);
}
a.push_back(temp);
}
ReadGraph(a);
return 0;
}