-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraph2.cpp
110 lines (94 loc) · 2.33 KB
/
Graph2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// Created by student on 13.12.2018.
//
#include "Graph2.h"
// Allocates memory for adjacency list
Graph2::Graph2(int b)
{
this->V = b;
adj = new list<iPair> [V];
parent = vector<int>(V, -1);
key = vector<int>(V, INF);
adjOfTree = new list<int>[V];
depth = vector<int>(V,0);
}
void Graph2::addEdge(int u, int v, int w)
{
adj[u].push_back(make_pair(v, w));
adj[v].push_back(make_pair(u, w));
}
void Graph2::prim() {
priority_queue< iPair, vector <iPair> , greater<iPair> > pq;
int src = 0; //burası
vector<bool> inMST(V, false);
pq.push(make_pair(0, src));
key[src] = 0;
while (!pq.empty()) {
int u = pq.top().second;
pq.pop();
inMST[u] = true;
list< pair<int, int> >::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i) {
int v = (*i).first;
int weight = (*i).second;
if (inMST[v] == false && key[v] > weight) {
key[v] = weight;
pq.push(make_pair(key[v], v));
parent[v] = u;
}
}
}
}
int Graph2::findDistance(int s, int t) {
int ds = depth[s];
int dt = depth[t];
int curmax= 0;
if(ds>dt){
int leng = ds-dt;
for(int i = 0; i < leng;++i){
curmax = max(curmax,key[s]);
s= parent[s];
}
} else {
int leng = dt-ds;
for(int i = 0;i< leng;++i){
curmax = max(curmax,key[t]);
t= parent[t];
}
}
int lengt = min(dt,ds);
while(lengt != 0){
if(s == t){
break;
}
curmax = max(curmax,key[s]);
curmax = max(curmax,key[t]);
s = parent[s];
t= parent[t];
lengt--;
}
return curmax;
}
void Graph2::toAdjMatrix() {
for( int i = 1 ; i < V ; i++){
adjOfTree[parent[i]].push_back(i);
}
}
void Graph2::findDepth() {
queue<int> q ;
queue<int> d;
int source = 0; //burası
d.push(0);
q.push(source);
while(q.size() != 0){
int current = q.front();
depth[current] = d.front();
q.pop();
d.pop();
list<int>::iterator i;
for (i = adjOfTree[current].begin(); i != adjOfTree[current].end(); ++i) {
q.push(*i);
d.push(depth[current]+1);
}
}
}