日期:2014-05-18  浏览次数:20779 次

C#算法结构
第二题
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Exame
{
  //表达式节点,
  //其中Exp可以表示为对其他节点的引用,格式为['NodeName']的形式,比如['a']+['b']表示 Name=="a"的节点的值 “加上” Name="b"的节点的值
  public struct ExpNode
  {
  public string Name; //名称
  public string Exp; //表达式:可以为直接量:比如:12,30.0.也可能为表达式:['a']+['b'].
  public ExpNode(string name, string exp)
  {
  this.Name = name;
  this.Exp = exp;
  }
  public override string ToString()
  {
  return Name;
  }
  } 
   
  class Program
  {
  static void Main(string[] args)
  {
  ExpNode[] nodes = new ExpNode[]
  {
  new ExpNode("a","['b']+['c']"),
  new ExpNode("b","['e']-['c']"),
  new ExpNode("c","['e']+['d']"),
  new ExpNode("d","10"),
  new ExpNode("e","['d']+2")
  };

  /*在这里写出排序算法,对Nodes进行排序,得出计算的先后顺序。并且通过Console输出:
  正确的结果是: d e c b a * 
  * 假定:表达式不会循环引用。
  */
  foreach (ExpNode n in nodes)
  Console.Write(n);
  }
  }
}


------解决方案--------------------
C# code
 
using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
namespace Exame
{
//表达式节点,
//其中Exp可以表示为对其他节点的引用,格式为['NodeName']的形式,比如['a']+['b']表示 Name=="a"的节点的值 “加上” Name="b"的节点的值
public struct ExpNode
{
public string Name;  //名称
public string Exp;  //表达式:可以为直接量:比如:12,30.0.也可能为表达式:['a']+['b'].
public ExpNode(string name, string exp)
{
this.Name = name;
this.Exp = exp;
}
public override string ToString()
{
return Name;
}
}

class Program
{
static void Main(string[] args)
{
ExpNode[] nodes = new ExpNode[]
{
new ExpNode("a","['b']+['c']"),
new ExpNode("b","['e']-['c']"),
new ExpNode("c","['e']+['d']"),
new ExpNode("d","10"),
new ExpNode("e","['d']+2"),

};

/*************************************************************************/


Dictionary <string,int> nodeindex=new Dictionary <string,int>();
//建立节点名字索引关联
int count=0;
foreach(ExpNode node in nodes)
{
nodeindex.Add(node.Name,count++);
}

//建立节点拓扑邻接矩阵
int[,] map=new int[nodes.Length,nodes.Length];
Array.Clear(map,0,nodes.Length*nodes.Length);
foreach(ExpNode node in nodes)
{
if(node.Exp.Contains("+")||node.Exp.Contains("-"))
{
string[] temp=node.Exp.Split(new char[]{'+','-'},StringSplitOptions.RemoveEmptyEntries);
foreach(string s in temp)

if(s.Contains(&q