我有这样的方法:
边缘就像这样
4这是节点计数
1 2 1前两个值是顶点,第三个元素是边的权重
4 1 2
2 3 2
1 3 5
public static List<Tuple<long,long>>[] WeightedGraph(long NodeCount,long[][] edges)
{
List<Tuple<long, long>>[] Weightedgraph = new List<Tuple<long, long>>[NodeCount + 1];
for(int i=0; i<Weightedgraph.Length;i++)
{
Weightedgraph[i] = new List<Tuple<long, long>>();
}
foreach(var vertex in edges)
{
**Weightedgraph[vertex[0]].Add();**
}
}
我如何完成**部分?
答案 0 :(得分:2)
最简单的方法是使用Tuple.Create(long, long)
:
public static List<Tuple<long, long>>[] WeightedGraph(long NodeCount, long[][] edges)
{
List<Tuple<long, long>>[] weightedgraph = new List<Tuple<long, long>>[NodeCount + 1];
for (int i = 0; i < weightedgraph.Length; i++)
{
weightedgraph[i] = new List<Tuple<long, long>>();
}
foreach (var vertex in edges)
{
weightedgraph[vertex[0]].Add(Tuple.Create(1L, 2L));
}
return weightedgraph;
}
但是请注意,对于C#7或更高版本,您可以使用the (x, y)
"value tuple" syntax简化操作并为元组元素提供更有意义的名称。
在下面的示例中,我修改了您的代码以调用元组元素X和Y:
public static List<(long X, long Y)>[] WeightedGraph(long nodeCount, long[][] edges)
{
var weightedgraph = new List<(long X, long Y)>[nodeCount + 1];
for (int i = 0; i < weightedgraph.Length; i++)
{
weightedgraph[i] = new List<(long X, long Y)>();
}
foreach (var vertex in edges)
{
weightedgraph[vertex[0]].Add((1L, 2L));
}
return weightedgraph;
}
答案 1 :(得分:1)
让我们添加可读性(该索引表示什么):
// I've changed NodeCount into int:
// do you really want a graph with more than 2e9 vertexes?
public static List<Tuple<long,long>>[] WeightedGraph(int NodeCount, long[][] edges) {
//TODO: validate NodeCount and edges
// Naming: "WeightedGraph" is the method's name; "result" is what we return
// Initialization: we want
List<Tuple<long, long>>[] result = Enumerable
.Range(0, NodeCount) // NodeCount vertexes
.Select(node => new List<Tuple<long, long>>()) // Each has a List<T> of edges
.ToArray(); // Organized as an array
foreach (var edge in edges) {
// Let's add readability end decrypt edges format
int vertexFrom = (int) (edge[0]);
long vertexTo = edge[1];
long edgeWeight = edge[2];
result[vertexFrom].Add(Tuple.Create(vertexTo, edgeWeight));
}
return result;
}