public KruskalMst(EdgeWeightedGraph graph) { mst = new Queue <Edge>(); var prioryQueue = new MinPQ <Edge>(); foreach (var edge in graph.GetEdges()) { prioryQueue.Insert(edge); } var ds = new DisjointSet(graph.Vertices); while (!prioryQueue.IsEmpty() && mst.Count < graph.Vertices - 1) { var edge = prioryQueue.DelMin(); int vertex = edge.Either(); int otherVertex = edge.Other(vertex); if (ds.Connected(vertex, otherVertex)) { continue; } ds.Union(vertex, otherVertex); mst.Enqueue(edge); } }
/// <summary> /// Compute a minimum spanning tree (or forest) of an edge-weighted graph. /// </summary> /// <param name="g">g the edge-weighted graph</param> public KruskalMST(EdgeWeightedGraph g) { // more efficient to build heap by passing array of edges var pq = new MinPQ<EdgeW>(); foreach (var e in g.Edges()) { pq.Insert(e); } // run greedy algorithm var uf = new UF(g.V); while (!pq.IsEmpty() && _mst.Size() < g.V - 1) { var e = pq.DelMin(); var v = e.Either(); var w = e.Other(v); if (!uf.Connected(v, w)) { // v-w does not create a cycle uf.Union(v, w); // merge v and w components _mst.Enqueue(e); // add edge e to mst _weight += e.Weight; } } // check optimality conditions //assert check(G); }
public LazyPrimMST(EdgeWeightedGraph graph) { prioryQueue = new MinPQ <Edge>(); marked = new bool[graph.Vertecies]; mst = new Queue <Edge>(); Visit(graph, 0); while (!prioryQueue.IsEmpty()) { var edge = prioryQueue.DelMin(); int vertex = edge.Either(); int otherVertex = edge.Other(vertex); if (marked[vertex] && marked[otherVertex]) { continue; } mst.Enqueue(edge); if (!marked[vertex]) { Visit(graph, vertex); } if (!marked[otherVertex]) { Visit(graph, otherVertex); } } }
private readonly Collections.Queue <EdgeW> _mst = new Collections.Queue <EdgeW>(); // edges in MST /// <summary> /// Compute a minimum spanning tree (or forest) of an edge-weighted graph. /// </summary> /// <param name="g">g the edge-weighted graph</param> public KruskalMST(EdgeWeightedGraph g) { // more efficient to build heap by passing array of edges var pq = new MinPQ <EdgeW>(); foreach (var e in g.Edges()) { pq.Insert(e); } // run greedy algorithm var uf = new UF(g.V); while (!pq.IsEmpty() && _mst.Size() < g.V - 1) { var e = pq.DelMin(); var v = e.Either(); var w = e.Other(v); if (!uf.Connected(v, w)) { // v-w does not create a cycle uf.Union(v, w); // merge v and w components _mst.Enqueue(e); // add edge e to mst _weight += e.Weight; } } // check optimality conditions //assert check(G); }
public KruskalMST(EdgeWeightedGraph ewg) { this.g = ewg; minPQ = new MinPQ <Edge>(g.E()); mstEdges = new Queue <Edge>(); //first we need to create a priority queue to store all Edges int either, other; foreach (Edge edge in ewg.Edges()) { //either = edge.Either(); //other = edge.Other(either); //if(either<other) //insert the same edge once only when either<other; minPQ.Insert(edge); } Edge currrent; Utils.UF uf = new Utils.UF(g.V()); //instantiate the union find variable //second, we take min from the PQ one at a time and insert to the queue if both ends are not connected yet while (!minPQ.IsEmpty() && mstEdges.Count < (this.g.V() - 1)) { currrent = minPQ.DelMin(); either = currrent.Either(); other = currrent.Other(either); if (!uf.IsConnected(either, other)) //only add the edge into the final queue if both ends are not connected { mstEdges.Enqueue(currrent); uf.Union(either, other); } } }
static void Main(string[] args) { var processorNum = int.Parse(Console.ReadLine()); var jobNum = int.Parse(Console.ReadLine()); var jobs = new Job[jobNum]; for (var i = 0; i < jobNum; i++) { var jobDesc = Console.ReadLine().Split(' '); jobs[i] = new Job(jobDesc[0], double.Parse(jobDesc[1])); } Array.Sort(jobs); var processors = new MinPQ <Processor>(processorNum); for (var i = 0; i < processorNum; i++) { processors.Insert(new Processor()); } for (var i = jobs.Length - 1; i >= 0; i--) { var min = processors.DelMin(); min.Add(jobs[i]); processors.Insert(min); } while (!processors.IsEmpty()) { Console.WriteLine(processors.DelMin()); } }
public void ShouldReturnTrueIfMinPqIsEmpty() { // Arrange var minPQ = new MinPQ <int>(); // Act var result = minPQ.IsEmpty(); // Assert Assert.IsTrue(result); }
static void Main(string[] args) { // 输入格式: buy 20.05 100 var buyer = new MaxPQ <Ticket>(); var seller = new MinPQ <Ticket>(); var n = int.Parse(Console.ReadLine()); for (var i = 0; i < n; i++) { var ticket = new Ticket(); var item = Console.ReadLine().Split(' '); ticket.Price = double.Parse(item[1]); ticket.Share = int.Parse(item[2]); if (item[0] == "buy") { buyer.Insert(ticket); } else { seller.Insert(ticket); } } while (!buyer.IsEmpty() && !seller.IsEmpty()) { if (buyer.Max().Price < seller.Min().Price) { break; } var buy = buyer.DelMax(); var sell = seller.DelMin(); Console.Write("sell $" + sell.Price + " * " + sell.Share); if (buy.Share > sell.Share) { Console.WriteLine(" -> " + sell.Share + " -> $" + buy.Price + " * " + buy.Share + " buy"); buy.Share -= sell.Share; buyer.Insert(buy); } else if (buy.Share < sell.Share) { sell.Share -= buy.Share; seller.Insert(sell); Console.WriteLine(" -> " + buy.Share + " -> $" + buy.Price + " * " + buy.Share + " buy"); } else { Console.WriteLine(" -> " + sell.Share + " -> $" + buy.Price + " * " + buy.Share + " buy"); } } }
public void ShouldReturnFalseIfMinPqIsNotEmpty() { // Arrange var minPQ = new MinPQ <int>(); minPQ.Insert(5); // Act var result = minPQ.IsEmpty(); // Assert Assert.IsFalse(result); }
// Relax(u, v, w): // if(d[v] > d[u] + w(u, v)) // d[v] = d[u] + w(u, v) private void dijkstra(EdgeWeightedDigraph graph, int vertex) { pq.Insert(vertex, 0.0); while (!pq.IsEmpty()) { int v = pq.DelMin(); foreach (DirectedWeightedEdge edge in graph.Adj(v)) { Relax(edge); } } }
void PriorityQueueTest() { var strArr = FileHandler.ReadFileAsStrArr("words3.txt"); var qp = new MinPQ <string>(strArr.Length); foreach (var item in strArr) { qp.Insert(item); } while (!qp.IsEmpty()) { Console.WriteLine(qp.DelMin()); } Console.ReadKey(); }
public LazyPrimMST(EdgeWeightedGraph g) { _marked = new bool[g.V]; _mst = new NodeQueue <Edge>(); pq = new MinPQ <Edge>(g.E);//MinPQ没有实现自动调整大小,先将就着用吧。 Visit(g, 0); while (!pq.IsEmpty()) { var e = pq.DelMin(); var v = e.Either(); v = !_marked[v] ? v : e.Other(v);//至少会有一条边已在生成树中。 if (!_marked[v]) { _mst.Enqueue(e); Visit(g, v); } } }
public KruskaMST(EdgeWeightedGraph g) { m_mst = new Queue <Edge>(); MinPQ <Edge> pq = new MinPQ <Edge>(g.Edges()); UnionFind uf = new UnionFind(g.V()); while (!pq.IsEmpty() && m_mst.Count < g.V() - 1) { Edge e = pq.DeleteTop(); int v = e.Either(); int w = e.Other(v); if (uf.Connected(v, w)) { continue; } uf.Union(v, w); m_mst.Enqueue(e); } }
private void AstarSP(EdgeWeightedDigraph graph, int vertex, int target) { pq.Insert(vertex, 0.0); while (!pq.IsEmpty()) { int v = pq.DelMin(); if (v == target) { break; } foreach (DirectedWeightedEdge edge in graph.Adj(v)) { Relax(edge, target); } } }
public KruskalMST(EdgeWeightedGraph g) { MinPQ<Edge> pq = new MinPQ<Edge>(); foreach (Edge e in g.Edges()) pq.Insert(e); Part1.QuickUnion uf = new Part1.QuickUnion(g.V()); while (!pq.IsEmpty() && this._mst.Count < g.V() - 1) { Edge e = pq.DelMin(); int v = e.Either(); int w = e.Other(v); if (!uf.IsConnected(v, w)) { uf.Union(v, w); this._mst.Enqueue(e); this.Weight += e.Weight(); } } }
public LazyPrimMST(EdgeWeightedGraph ewg) { g = ewg; int vertexNum = g.V(); int edgeNum = g.E(); isVisited = new bool[vertexNum]; minQueue = new MinPQ <Edge>(edgeNum); mstEdges = new Queue <Edge>(); Visit(0); Edge eCurrent; int either, other; while (!minQueue.IsEmpty()) { eCurrent = minQueue.DelMin(); either = eCurrent.Either(); other = eCurrent.Other(either); if (!isVisited[either] || !isVisited[other]) //at least one end of the edge should not be visited, otherwise we will have a loop { mstEdges.Enqueue(eCurrent); if (!isVisited[either]) { Visit(either); } else { Visit(other); } } } //for(int i=0;i<vertexNum;i++) //{ // if(!isVisisted[i]) // { // } //} }
static void Main(string[] args) { int n = 1000000; MinPQ <CubeSum> pq = new MinPQ <CubeSum>(); Console.WriteLine("正在初始化"); for (int i = 0; i <= n; i++) { pq.Insert(new CubeSum(i, i)); } FileStream ostream = new FileStream("./result.txt", FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(ostream); Console.WriteLine("正在写入文件……"); CubeSum prev = new CubeSum(-1, -1); long pairCount = 0; while (!pq.IsEmpty()) { CubeSum s = pq.DelMin(); if (s.sum == prev.sum) { sw.WriteLine(s + " = " + prev.i + "^3 + " + prev.j + "^3"); pairCount++; } if (s.j < n) { pq.Insert(new CubeSum(s.i, s.j + 1)); } prev = s; } sw.WriteLine("共找到" + pairCount + "对数据"); Console.WriteLine("共找到" + pairCount + "对数据"); sw.Close(); Console.WriteLine("结果已经保存到程序所在目录下的 result.txt 文件中"); }
/// <summary> /// 进行一次测试。 /// </summary> /// <param name="m">测试使用的 m 值。</param> /// <param name="n">测试使用的 n 值。</param> /// <returns></returns> static long test(int m, int n) { var pq = new MinPQ <EuclideanDistance3D>(m); int[] x = new int[n]; int[] y = new int[n]; int[] z = new int[n]; Random random = new Random(); for (int i = 0; i < n; i++) { x[i] = random.Next(); y[i] = random.Next(); z[i] = random.Next(); } Stopwatch sw = new Stopwatch(); sw.Start();// 开始计时 for (int i = 0; i < m; i++) { // 先插入 m 个记录 pq.Insert(new EuclideanDistance3D(x[i], y[i], z[i])); } for (int i = m; i < n; i++) { // 插入剩余 n-m 个记录 pq.DelMin(); pq.Insert(new EuclideanDistance3D(x[i], y[i], z[i])); } while (pq.IsEmpty()) { pq.DelMin(); } sw.Stop();// 停止计时 return(sw.ElapsedMilliseconds); }
/// <summary> /// run Prim's algorithm /// </summary> /// <param name="g"></param> /// <param name="s"></param> private void Prim(EdgeWeightedGraph g, int s) { Scan(g, s); while (!_pq.IsEmpty()) { // better to stop when mst has V-1 edges var e = _pq.DelMin(); // smallest edge on pq int v = e.Either(), w = e.Other(v); // two endpoints //assert marked[v] || marked[w]; if (_marked[v] && _marked[w]) { continue; // lazy, both v and w already scanned } _mst.Enqueue(e); // add e to MST _weight += e.Weight; if (!_marked[v]) { Scan(g, v); // v becomes part of tree } if (!_marked[w]) { Scan(g, w); // w becomes part of tree } } }