POJ

来源:互联网 发布:卡尔曼滤波算法 应用 编辑:程序博客网 时间:2024/06/14 11:35

Tram network in Zagreb consists of a number of intersections and rails connecting some of them. In every intersection there is a switch pointing to the one of the rails going out of the intersection. When the tram enters the intersection it can leave only in the direction the switch is pointing. If the driver wants to go some other way, he/she has to manually change the switch.
建图,点与相连的第一个点边值为0,与其他点相连为1,与不相连点的边为INF。
用dijkstra直接求。

#include<queue>#include<stdio.h>#include<string>#include<iostream>#include<map>#include<limits>#include<math.h>using namespace std;#define N 1000#define LL long long int#define pow(a) ((a)*(a))#define INF 0x3f3f3f3f#define mem(arr,a) memset(arr,a,sizeof(arr))int n, a, b;int cost[N][N];int vis[N];int d[N];void dijkstra(){    mem(d, INF);    mem(vis, 0);    d[a] = 0;    int cnt = 0;    while (1){        cnt++;        int v = -1;        for (int i = 1; i <= n; i++){            if (!vis[i] && (v == -1 || d[i] < d[v]))v = i;        }        if (v == -1)break;        vis[v] = 1;        for (int i = 1; i <= n; i++){            if (d[i]>d[v] + cost[v][i]){                d[i] = d[v] + cost[v][i];            }        }    }    if (d[b]!=INF)    cout << d[b] << endl;    else cout << -1 << endl;}int main(){    cin >> n >> a >> b;    mem(cost, INF);    for (int i = 1; i <= n; i++){        int t; cin >> t;        int to; cin >> to;        cost[i][to] = 0;        for (int j = 1; j < t; j++){            cin >> to;            cost[i][to] = 1;        }    }    dijkstra();}
原创粉丝点击