Tram POJ - 1847
题目链接:https://vjudge.net/problem/POJ-1847
思路:想从A到B使用开关少,想清楚了就是个简单的最短路,可以把不用开开关为权值0,
要开开关为权值1,就是求A到B开开关最少的次数,题目说了,每行第一个点是第 i-th点和他正好数开关开的方向连接。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <queue> 6 #include <stack> 7 #include <string> 8 #include <map> 9 #include <cmath> 10 #include <iomanip> 11 using namespace std; 12 13 typedef long long LL; 14 #define inf 1e9 15 #define rep(i,j,k) for(int i = (j); i <= (k); i++) 16 #define rep__(i,j,k) for(int i = (j); i < (k); i++) 17 #define per(i,j,k) for(int i = (j); i >= (k); i--) 18 #define per__(i,j,k) for(int i = (j); i > (k); i--) 19 20 const int N = 110; 21 int head[N]; 22 bool vis[N]; 23 int dis[N]; 24 int cnt; 25 int n,s,t; 26 27 struct Edge{ 28 int to; 29 int w; 30 int next; 31 }e[N * N]; 32 33 struct node{ 34 int pos; 35 int w; 36 37 bool friend operator< (const node& a,const node& b){ 38 return a.w > b.w; 39 } 40 }; 41 42 void add(int u,int v,int w){ 43 e[cnt].to = v; 44 e[cnt].w = w; 45 e[cnt].next = head[u]; 46 head[u] = cnt++; 47 } 48 49 void dijkstra(){ 50 51 rep(i,1,n) vis[i] = false; 52 rep(i,1,n) dis[i] = inf; 53 dis[s] = 0; 54 55 priority_queue<node> que; 56 que.push(node{s,0}); 57 58 int pos,v,w; 59 while(!que.empty()){ 60 pos = que.top().pos; 61 que.pop(); 62 63 if(vis[pos]) continue; 64 vis[pos] = true; 65 66 for(int o = head[pos]; ~o; o = e[o].next){ 67 v = e[o].to; 68 w = e[o].w; 69 70 if(!vis[v] && dis[pos] + w < dis[v]){ 71 dis[v] = dis[pos] + w; 72 73 que.push(node{v,dis[v]}); 74 } 75 } 76 } 77 78 if(dis[t] == inf) cout << "-1" << endl; 79 else cout << dis[t] << endl; 80 } 81 82 int main(){ 83 84 scanf("%d%d%d",&n,&s,&t); 85 86 rep(i,1,n) head[i] = -1; 87 int cnt = 0; 88 89 int tot,v; 90 rep(u,1,n){ 91 cin >> tot; 92 93 rep(i,1,tot){ 94 cin >> v; 95 96 if(i == 1) add(u,v,0); 97 else add(u,v,1); 98 } 99 } 100 dijkstra(); 101 102 getchar(); getchar(); 103 return 0; 104 }
1