Advertisement
Guest User

Untitled

a guest
Apr 30th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.86 KB | None | 0 0
  1. import edu.princeton.cs.algs4.In;
  2. import edu.princeton.cs.algs4.LinkedBag;
  3. import edu.princeton.cs.algs4.Point2D;
  4. import edu.princeton.cs.algs4.SeparateChainingHashST;
  5. import edu.princeton.cs.algs4.StdOut;
  6.  
  7. public class EuclideanEdgeWeightedGraph {
  8. private int V;
  9. private int E;
  10. private SeparateChainingHashST<Point2D, LinkedBag<EuclideanEdge>> adj;
  11.  
  12. // Initialize an empty Euclidean edge-weighted graph from an input stream.
  13. public EuclideanEdgeWeightedGraph(In in) {
  14. this(in.readInt());
  15. int E = in.readInt();
  16. adj = new SeparateChainingHashST<Point2D, LinkedBag<EuclideanEdge>>();
  17. for (int i = 0; i < E; i++) {
  18. int v = in.readInt();
  19. int w = in.readInt();
  20. double weight = in.readDouble();
  21. Edge e = new Edge(v, w, weight);
  22. addEdge(e);
  23. }
  24. }
  25.  
  26. // Number of vertices in this Euclidean edge-weighted graph.
  27. public int V() {
  28. return V;
  29. }
  30.  
  31. // Number of edges in this Euclidean edge-weighted graph.
  32. public int E() {
  33. return E;
  34. }
  35.  
  36. // Add an undirected edge to this Euclidean edge-weighted graph.
  37. public void addEdge(EuclideanEdge e) {
  38. int v = e.either();
  39. int w = e.other(v);
  40. validateVertex(v);
  41. validateVertex(w);
  42. adj[v].add(e);
  43. adj[w].add(e);
  44. E++;
  45. }
  46.  
  47. // Edges incident on vertex v.
  48. public Iterable<EuclideanEdge> adj(Point2D v) {
  49. validateVertex(v);
  50. return adj[v];
  51. }
  52.  
  53. // All the edges in this Euclidean edge-weighted graph.
  54. public Iterable<EuclideanEdge> edges() {
  55. LinkedBag<EuclideanEdge> bag = new LinkedBag<EuclideanEdge>();
  56. for (Point2D v : adj.keys()) {
  57. int selfLoops = 0;
  58. for (EuclideanEdge e : adj(v)) {
  59. if (e.other(v).hashCode() > v.hashCode()) {
  60. bag.add(e);
  61. }
  62. else if (e.other(v).equals(v)) {
  63. if (selfLoops % 2 == 0) bag.add(e);
  64. selfLoops++;
  65. }
  66. }
  67. }
  68. return bag;
  69. }
  70.  
  71. // A string representation of this Euclidean edge-weighted graph.
  72. public String toString() {
  73. StringBuilder s = new StringBuilder();
  74. s.append(V + " " + E + "\n");
  75. for (Point2D v : adj.keys()) {
  76. s.append(v + ": ");
  77. for (EuclideanEdge e : adj(v)) {
  78. s.append(e + " ");
  79. }
  80. s.append("\n");
  81. }
  82. return s.toString();
  83. }
  84.  
  85. // Test client. [DO NOT EDIT]
  86. public static void main(String[] args) {
  87. In in = new In(args[0]);
  88. EuclideanEdgeWeightedGraph G = new EuclideanEdgeWeightedGraph(in);
  89. for (EuclideanEdge e : G.edges()) {
  90. StdOut.println(e);
  91. }
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement