POJ 1847

题意: 一张图中,每个结点一开始都指向了一个相邻点。可以改变每个点指向的点。求一条从A到B的路,使用最少改变路上点的指向的次数,若不村在输出-1

 

思路:Dijkstra。i指向j,则map[i][j] = 0, 其他的都等于1。以此建立模型。

 

统计:288k, 0m, 1Y

 

#include <iostream> #include <queue> #include <vector> #define F(i,a,b) for (int i=a;i<=b;i++) using namespace std; bool mk[102][102]; int map[102][102], linkn[102], start, e, n ; struct State { int v, now; State() {} State ( int a, int b ) { now = a, v = b; } bool operator < ( const State& b ) const { return v > b.v ; } }; priority_queue< State > heap; void dijk() { int v; State s ( start, 0 ); mk[start][0] = true; heap.push ( s ); while ( !heap.empty() ) { s = heap.top(); v = s.now; heap.pop(); if ( v == e ) { cout << s.v ; return; } if ( !mk[ map[v][1] ][ s.v ] ) { heap.push ( State ( map[v][1] , s.v ) ); mk[ map[v][1] ][ s.v ] = true; } F ( i, 2, linkn[v] ) { if ( !mk[ map[v][i] ][ s.v+1 ] ) { mk[ map[v][i] ][ s.v+1 ] = true; heap.push ( State ( map[v][i], s.v+1 ) ); } } } cout << "-1/n"; } int main() { scanf ( "%d%d%d", &n, &start, &e ); F ( i, 1, n ) { scanf ( "%d", &linkn[i] ); F ( j, 1, linkn[i] ) scanf ( "%d", &map[i][j] ); } dijk(); return 0; }

你可能感兴趣的:(POJ 1847)