├── Dijkstra(single source shortest path).cpp ├── Kruskal's Algo for MST.cpp ├── Prim's Algo for MST.cpp ├── README.md ├── dijkstra.py ├── floyd.py ├── kruskal.py ├── prim.py └── priodict.py /Dijkstra(single source shortest path).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long 4 | #define ld long double 5 | #define pb push_back 6 | #define pf push_front 7 | #define mp make_pair 8 | #define F first 9 | #define S second 10 | #define mod 1000000007 11 | #define md 998244353 12 | #define INF INT_MAX 13 | #define vl vector 14 | #define vi vector 15 | #define pi pair 16 | #define pl pair 17 | #define vpl vector 18 | #define vpi vector 19 | #define ml map 20 | #define mi map 21 | #define m(a,b) map 22 | #define rep(i,n) for(int i=1;i<=n;i++) 23 | #define mxn 100005 24 | #define printfloat(y) cout< q; 35 | bool processed[mxn]; 36 | setval(processed,false); 37 | dist[source]=0; 38 | q.push({0,source}); 39 | while (!q.empty()) { 40 | int a=q.top().second; 41 | q.pop(); 42 | if(processed[a]){ 43 | continue; 44 | } 45 | processed[a]=true; 46 | for(auto u :adj[a]){ 47 | int b=u.first; 48 | ll w=u.second; 49 | if(dist[a]+w>t; 77 | while(t--){ 78 | int n,m,source=1,destination; 79 | cin>>n>>m; 80 | destination=n; 81 | for(int j=0;j>a>>b>>w; 85 | adj[a].pb(mp(b,w)); 86 | adj[b].pb(mp(a,w)); 87 | } 88 | for(int i=1;i<=n;i++){ 89 | dist[i]=1e12; 90 | } 91 | // cin>>source; //if source is given 92 | // cin>>destination; // if destination is given 93 | dijkstra(source); 94 | // cout< 2 | using namespace std; 3 | #define ll long long 4 | #define ld long double 5 | #define pb push_back 6 | #define pf push_front 7 | #define mp make_pair 8 | #define F first 9 | #define S second 10 | #define mod 1000000007 11 | #define INF INT_MAX 12 | #define vl vector 13 | #define vi vector 14 | #define pi pair 15 | #define pl pair 16 | #define vpl vector 17 | #define vpi vector 18 | #define ml map 19 | #define mi map 20 | #define m(a,b) map 21 | #define YesNo(f) if(f){cout<<"YES"< edgeList,vector &mstEdges){ 57 | int weight=0; 58 | for(edge i: edgeList){ 59 | if(ifMakingCycle(i.a,i.b)){ 60 | continue; 61 | } 62 | unionsets(i.a,i.b); 63 | weight+=i.w; 64 | mstEdges.pb(i); 65 | } 66 | return weight; 67 | } 68 | 69 | int main() 70 | { 71 | fastIO; 72 | // freopen("input.txt","r",stdin); 73 | // freopen("output.txt","w",stdout); 74 | int t=1; 75 | // cin>>t; 76 | while(t--){ 77 | int n,m,x,y; 78 | cin>>n>>m; 79 | vector edgeList(m); 80 | for(int j=0;j>edgeList[j].a>>edgeList[j].b>>edgeList[j].w; 82 | } 83 | sort(edgeList.begin(), edgeList.end(),comp); 84 | 85 | for(int i=1;i<=n;i++){ 86 | size[i]=1; 87 | reprs[i]=i; 88 | } 89 | vector mstEdges; //stores edges in the mst 90 | int weight=KruskalsMST(edgeList, mstEdges); //stores weight of the MST 91 | 92 | cout< 2 | using namespace std; 3 | #define ll long long 4 | #define ld long double 5 | #define pb push_back 6 | #define pf push_front 7 | #define mp make_pair 8 | #define F first 9 | #define S second 10 | #define mod 1000000007 11 | #define INF INT_MAX 12 | #define vl vector 13 | #define vi vector 14 | #define pi pair 15 | #define pl pair 16 | #define vpl vector 17 | #define vpi vector 18 | #define ml map 19 | #define mi map 20 | #define m(a,b) map 21 | #define YesNo(f) if(f){cout<<"YES"<,greater >q; 28 | 29 | int start=1; //Taking any node to start building the MST 30 | vi weight(n+1,INF); //ith position stores min value edge ending at i 31 | vpi parent(n+1,mp(-1,INF)); //stores parent of a node in the mst 32 | vi inMST(n+1,false); //stores if node i is included in MST 33 | 34 | q.push(mp(0,start)); //starting the MST 35 | weight[start]=0; 36 | 37 | while(!q.empty()){ 38 | int u=q.top().S; 39 | q.pop(); 40 | inMST[u]=true; //includes node u in MST 41 | 42 | for(auto i: adj[u]){ 43 | int v=i.F; 44 | int w=i.S; 45 | if(!inMST[v] && w>t; 70 | while(t--){ 71 | int n,m,x,y,w; 72 | cin>>n>>m; 73 | vpi adj[n+1]; 74 | for(int i=0;i>x>>y>>w; 76 | adj[x].pb(mp(y,w)); 77 | adj[y].pb(mp(x,w)); 78 | } 79 | vpi mstEdges; // stores the edges in MST 80 | int weight=PrimsMST(n,adj,mstEdges); //stores weight of the MST 81 | 82 | cout< new_len: 20 | graph[i][j] = new_len 21 | new_node = k 22 | if new_node: 23 | path[i][j].insert(-1, new_node) 24 | 25 | return graph, path 26 | 27 | def floyd_dict(graph): 28 | length = len(graph) 29 | path = {} 30 | 31 | for src in graph: 32 | path.setdefault(src, {}) 33 | for dst in graph[src]: 34 | if src == dst: 35 | continue 36 | path[src].setdefault(dst, [src,dst]) 37 | new_node = None 38 | 39 | for mid in graph: 40 | if mid == dst: 41 | continue 42 | 43 | new_len = graph[src][mid] + graph[mid][dst] 44 | if graph[src][dst] > new_len: 45 | graph[src][dst] = new_len 46 | new_node = mid 47 | if new_node: 48 | path[src][dst].insert(-1, new_node) 49 | 50 | return graph, path 51 | 52 | 53 | if __name__ == '__main__': 54 | ini = float('inf') 55 | graph_list = [ [0, 2, 1, 4, 5, 1], 56 | [1, 0, 4, 2, 3, 4], 57 | [2, 1, 0, 1, 2, 4], 58 | [3, 5, 2, 0, 3, 3], 59 | [2, 4, 3, 4, 0, 1], 60 | [3, 4, 7, 3, 1, 0]] 61 | 62 | graph_dict = { "s1":{"s1": 0, "s2": 2, "s10": 1, "s12": 4}, 63 | "s2":{"s1": 1, "s2": 0, "s10": 4, "s12": 2}, 64 | "s10":{"s1": 2, "s2": 1, "s10": 0, "s12":1}, 65 | "s12":{"s1": 3, "s2": 5, "s10": 2, "s12":0}, 66 | } 67 | 68 | #new_graph, path= floyd_dict(graph_dict) 69 | new_graph, path = floyd(graph_list) 70 | print new_graph, '\n\n\n', path 71 | -------------------------------------------------------------------------------- /kruskal.py: -------------------------------------------------------------------------------- 1 | def kruskal(graph): 2 | assert type(graph)==dict 3 | 4 | nodes = graph.keys() 5 | visited = set() 6 | path = [] 7 | next = None 8 | 9 | while len(visited) < len(nodes): 10 | distance = float('inf') 11 | for s in nodes: 12 | for d in nodes: 13 | if s in visited and d in visited or s == d: 14 | continue 15 | if graph[s][d] < distance: 16 | distance = graph[s][d] 17 | pre = s 18 | next = d 19 | 20 | path.append((pre, next)) 21 | visited.add(pre) 22 | visited.add(next) 23 | 24 | return path 25 | 26 | 27 | if __name__ == '__main__': 28 | graph_dict = { "s1":{"s1": 0, "s2": 6, "s10": 3, "s12": 4, "s5":3}, 29 | "s2":{"s1": 1, "s2": 0, "s10": 4, "s12": 3, "s5":4}, 30 | "s10":{"s1": 2, "s2": 6, "s10": 0, "s12":3, "s5":4}, 31 | "s12":{"s1": 1, "s2": 5, "s10": 2, "s12":0,"s5":2}, 32 | "s5":{"s1": 3, "s2": 5, "s10": 7, "s12":4,"s5":0}, 33 | } 34 | 35 | path = kruskal(graph_dict) 36 | print path 37 | 38 | -------------------------------------------------------------------------------- /prim.py: -------------------------------------------------------------------------------- 1 | def prim(graph, root): 2 | assert type(graph)==dict 3 | 4 | nodes = graph.keys() 5 | nodes.remove(root) 6 | 7 | visited = [root] 8 | path = [] 9 | next = None 10 | 11 | while nodes: 12 | distance = float('inf') 13 | for s in visited: 14 | for d in graph[s]: 15 | if d in visited or s == d: 16 | continue 17 | if graph[s][d] < distance: 18 | distance = graph[s][d] 19 | pre = s 20 | next = d 21 | path.append((pre, next)) 22 | visited.append(next) 23 | nodes.remove(next) 24 | 25 | return path 26 | 27 | 28 | if __name__ == '__main__': 29 | graph_dict = { "s1":{"s1": 0, "s2": 2, "s10": 3, "s12": 4, "s5":3}, 30 | "s2":{"s1": 1, "s2": 0, "s10": 4, "s12": 2, "s5":2}, 31 | "s10":{"s1": 2, "s2": 6, "s10": 0, "s12":3, "s5":4}, 32 | "s12":{"s1": 3, "s2": 5, "s10": 2, "s12":0,"s5":2}, 33 | "s5":{"s1": 3, "s2": 5, "s10": 2, "s12":4,"s5":0}, 34 | } 35 | 36 | path = prim(graph_dict, 's12') 37 | print path 38 | -------------------------------------------------------------------------------- /priodict.py: -------------------------------------------------------------------------------- 1 | # Priority dictionary using binary heaps 2 | # David Eppstein, UC Irvine, 8 Mar 2002 3 | 4 | from __future__ import generators 5 | 6 | class priorityDictionary(dict): 7 | def __init__(self): 8 | '''Initialize priorityDictionary by creating binary heap 9 | of pairs (value,key). Note that changing or removing a dict entry will 10 | not remove the old pair from the heap until it is found by smallest() or 11 | until the heap is rebuilt.''' 12 | self.__heap = [] 13 | dict.__init__(self) 14 | 15 | def smallest(self): 16 | '''Find smallest item after removing deleted items from heap.''' 17 | if len(self) == 0: 18 | raise IndexError, "smallest of empty priorityDictionary" 19 | heap = self.__heap 20 | while heap[0][1] not in self or self[heap[0][1]] != heap[0][0]: 21 | lastItem = heap.pop() 22 | insertionPoint = 0 23 | while 1: 24 | smallChild = 2*insertionPoint+1 25 | if smallChild+1 < len(heap) and \ 26 | heap[smallChild] > heap[smallChild+1]: 27 | smallChild += 1 28 | if smallChild >= len(heap) or lastItem <= heap[smallChild]: 29 | heap[insertionPoint] = lastItem 30 | break 31 | heap[insertionPoint] = heap[smallChild] 32 | insertionPoint = smallChild 33 | return heap[0][1] 34 | 35 | def __iter__(self): 36 | '''Create destructive sorted iterator of priorityDictionary.''' 37 | def iterfn(): 38 | while len(self) > 0: 39 | x = self.smallest() 40 | yield x 41 | del self[x] 42 | return iterfn() 43 | 44 | def __setitem__(self,key,val): 45 | '''Change value stored in dictionary and add corresponding 46 | pair to heap. Rebuilds the heap if the number of deleted items grows 47 | too large, to avoid memory leakage.''' 48 | dict.__setitem__(self,key,val) 49 | heap = self.__heap 50 | if len(heap) > 2 * len(self): 51 | self.__heap = [(v,k) for k,v in self.iteritems()] 52 | self.__heap.sort() # builtin sort likely faster than O(n) heapify 53 | else: 54 | newPair = (val,key) 55 | insertionPoint = len(heap) 56 | heap.append(None) 57 | while insertionPoint > 0 and \ 58 | newPair < heap[(insertionPoint-1)//2]: 59 | heap[insertionPoint] = heap[(insertionPoint-1)//2] 60 | insertionPoint = (insertionPoint-1)//2 61 | heap[insertionPoint] = newPair 62 | 63 | def setdefault(self,key,val): 64 | '''Reimplement setdefault to call our customized __setitem__.''' 65 | if key not in self: 66 | self[key] = val 67 | return self[key] --------------------------------------------------------------------------------