最近为了搞unity专门学了c#,为了验证一些基础语法,故意写了个最短路来学习。
但是交上去我发现效率异常的低,比c++低了很多,都快接近python的水平
这就很诡异了,是c#的效率真的如此不堪吗?还是说我是哪个地方应用不正确,还请dalao们赐教
P.S.(我大创预期做一个模拟大学的游戏,对寻路算法的效率比较敏感)
因为c#的stl(姑且这么叫吧)没有优先队列,就用sortedset(底层使用红黑树)重载比较器来曲线救国了
c#的读入不太友好,手写了个类似于快读的东西来方便读入
代码
using System;
using System.Collections.Generic;
using System.Collections;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
namespace HelloWorld_
{
class Common
{
public bool isdigit(int c)
{
if (c >= '0' && c <= '9') return true;
return false;
}
public bool isletter(int c)
{
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
return true;
return false;
}
public int read()
{
int x = 0, f = 1; int c = Console.Read();
while (!isdigit(c))
{
if (c == '-') f = -1;
c = Console.Read();
}
while (isdigit(c))
{
x = x * 10 + c - '0';
c = Console.Read();
}
return x * f;
}
public string readS()
{
string s = new string('a', 0); int c = Console.Read();
while (!isletter(c)) c = Console.Read();
while (isletter(c))
{
s += (char)c;
c = Console.Read();
}
return s;
}
}
public struct DijHeap
{
public int to;
public long w;
public DijHeap(int _to, long _w)
{
to = _to;
w = _w;
}
}
// 堆的比较器
public class HeapComparer : IComparer<DijHeap>
{
public int Compare(DijHeap x, DijHeap y)
{
if (x.w == y.w)
{
if (x.to == y.to) return 0;
return x.to > y.to ? 1 : -1;
}
return x.w > y.w ? 1 : -1;
}
}
struct Road
{
public int to;
public long w;
public Road(int _to, long _dis)
{
to = _to;
w = _dis;
}
}
class RoadSystem
{
const long inf = 0x3f3f3f3f;
const int N = 100000 + 100;
ArrayList[] e;
long[] dis;
int n;
bool[] vis;
public void init()
{
dis = new long[N];
n = 0;
vis = new bool[N];
e = new ArrayList[N];
for (int i = 0; i < N; i++)
e[i] = new ArrayList();
}
public void input()
{
Common com = new Common();
n = com.read();
int m = com.read(), S = com.read();
for (int i = 1; i <= m; i++)
{
int s = com.read(), t = com.read(), w = com.read();
e[s].Add(new Road(t, w));
}
CalcDis(S);
//Console.Write(dis[T]);
for (int i = 1; i <= n; i++)
if (dis[i] != inf)
Console.Write(dis[i]+" ");
else
Console.Write(((1L << 31) - 1)+" ");
//Console.WriteLine();
}
void CalcDis(int S)
{
SortedSet<DijHeap> dl = new SortedSet<DijHeap>(new HeapComparer());
for (int i = 0; i <= n; i++)
{
dis[i] = inf;
vis[i] = false;
}
dl.Add(new DijHeap(S, 0));
dis[S] = 0;
while (dl.Count != 0)
{
DijHeap now = dl.Min;
dl.Remove(now);
if (vis[now.to] == true)
continue;
vis[now.to] = true;
foreach (Road j in e[now.to])
if (dis[j.to] > dis[now.to] + j.w)
{
dis[j.to] = dis[now.to] + j.w;
dl.Add(new DijHeap(j.to, dis[j.to]));
}
}
}
}
class Program
{
static void Main(string[] args)
{
RoadSystem rs = new RoadSystem();
rs.init();
rs.input();
//Console.WriteLine(test[0]+"\n23");
//Console.ReadKey();
}
}
}