我想使用天真的方法在C#中实现我自己的优先级队列。我需要在Graph中使用PQ作为边缘来实现Prims算法。这是我到目前为止所做的:
public class Edge
{
private int v; // one vertex
private int w; // the other vertex
private int weight; // edge weight
public Edge(int v0, int w0, int weight0)
{
v = v0;
w = w0;
weight = weight0;
}
public Edge()
{
v = 0;
w = 0;
weight = 0;
}
public int get_weight()
{
return weight;
}
public int either()
{
return v;
}
public int the_other(int vertex)
{
if (vertex == v) return w;
else return v;
}
public int compareTo(Edge that)
{
if (this.get_weight() < that.get_weight()) return -1;
if (this.get_weight() < that.get_weight()) return 1;
else return 0;
}
public string to_str()
{
string s = v.ToString() + " " + weight.ToString() + " " + w.ToString() + '\n';
return s;
}
}
public class MyPriorityQueue_Edge
{
private List<Edge> q = new List<Edge>();
int size;
public MyPriorityQueue_Edge()
{
size = 0;
}
public void insert(Edge e)
{
q.Add(e);
size++;
}
Edge Min()
{
int min_weight = 1000;
Edge min_edge = new Edge();
foreach(Edge e in q)
if(e.get_weight()< min_weight)
min_edge = e;
return min_edge;
}
public Edge delmin()
{
Edge e = q.Min();
q.Remove(e);
size--;
return e;
}
public bool is_empty()
{
if (size == 0) return true;
else return false;
}
}
当我编译它时,编译器指向这一行:
边缘e = q.Min();
并说我没有处理异常&#34; System.Argument.Exception&#34;。如果你有任何想法我的程序有什么问题,如何解决或以其他方式实现我的想法,我很欣赏它。
答案 0 :(得分:1)
来自MSDN Enumerable.Min<TSource> Method (IEnumerable<TSource>)
如果类型TSource实现
IComparable<T>
,则此方法使用该实现来比较值。否则,如果类型TSource实现IComparable
,则该实现用于比较值。
您需要在Edge类中实现IComparable接口。
public class Edge : IComparable
然后添加CompareTo()方法。像
这样的东西public int CompareTo(object obj)
{
if (obj is Edge)
{
Edge other = (Edge)obj;
return this.compareTo(other); // you already implemented this in your Edge class
}
else
{
throw new InvalidOperationException();
}
}