无法输入图形

Unable to Input the graph

本文关键字:图形 输入      更新时间:2023-10-16

我在c++中解决问题http://www.spoj.com/problems/SHOP/,但我无法弄清楚如何输入图形以进一步应用Dijkstra算法。下面是图表格式——
4 3
3
4 2 X 4

第一行表示&
"S" &"D"-分别表示源和目的
数字-表示通过该块所需的时间,"X"-表示禁止进入区域。
如何根据DIjkstra算法的要求转换下面的图中的节点和边。我不知道怎样把地图转换成图表。

不需要转换。想象你在某个点(i,j)(我假设每个方格允许你走四步)。然后,你可以去(i + 1, j), (i, j + 1), (i - 1, j), (i, j - 1)如果:

1)该索引在表内2)该索引未标记X

你给了平方S的位置你的Dijkstra算法。每次你向你的数据结构中加入新的允许平方集。一旦你到达D的位置,你打印它。

此外,这个问题对我来说似乎并不重要,所以你可以使用一个简单的BFS,也可以使用一个队列。但是如果你想用Dijkstra算法去不同的方格会有不同的代价。如果您使用优先队列而不是队列。例如,您可以使用如下的数据结构集:

 int dist[][]; // this contains the cost to get to some square
//dist is initialized with a large number
struct node{
    int i, j; //location
    node(int ii, int jj){
        i = ii;
        j = jj;
    }
    bool operator < (node &n)const{ //set in c++ will use this to sort
        if(dist[i][j] == dist[n.i][n.j]) return i < n.i || j < n.j; //this is necessary
        return dist[i][j] < dist[n.i][n.j];
    }
};
set <node> q;
int main(){
    //initialized dist with large number
    dist[S.i][S.j] = 0; //we start from source
    q.push(node(S.i, S.j));
    while(true){
        //pick the first element in set
        //this element has the smallest cost
        //update dist using this node if necessary
        //for every node that you update remove from q and add it again
        //this way the location of that node will be updated in q
        //if you see square 'D' you are done and you can print dist[D.i][D.j]
    }
    return 0;
}

不需要将矩阵转换为节点和边。您可以创建包含(行号,列号,时间)的结构,其中时间将表示从源到达此坐标所花费的时间。现在以key为时间,创建这个结构的最小堆。现在从最小堆中提取元素(最初源将在最小堆中,时间为0),并将相邻元素推入最小堆(只有那些未访问且不包含X的元素)。继续这样做,直到提取的元素不是目标。