UVA10917 Walk Through the Forest
题目大意:Jimmy下班后决定每天沿着一条不同的路径回家,欣赏不同的风景。他打算只沿着满足如下条件的(A,B)道路走:存在一条从B出发回家的路,比所有从A出发回家的路径都短。你的任务是计算一共有多少条不同的回家路径。其中公司的编号为1,家的编号为2.
题解:算出每个点到2的最短路,对于每条边(i,j),“存在一条从B出发回家的路,比所有从A出发回家的路径都短”,即d[B] < d[A],说明能从A走到B,于是建新图A->B。不难发现是一个DAG(因为有环就会出现逻辑矛盾)。建反图dp即可
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <cstdlib> 5 #include <algorithm> 6 #include <queue> 7 #include <vector> 8 #include <map> 9 #include <string> 10 #include <cmath> 11 #define min(a, b) ((a) < (b) ? (a) : (b)) 12 #define max(a, b) ((a) > (b) ? (a) : (b)) 13 #define abs(a) ((a) < 0 ? (-1 * (a)) : (a)) 14 template<class T> 15 inline void swap(T &a, T &b) 16 { 17 T tmp = a;a = b;b = tmp; 18 } 19 inline void read(int &x) 20 { 21 x = 0;char ch = getchar(), c = ch; 22 while(ch < '0' || ch > '9') c = ch, ch = getchar(); 23 while(ch <= '9' && ch >= '0') x = x * 10 + ch - '0', ch = getchar(); 24 if(c == '-') x = -x; 25 } 26 const int INF = 0x3f3f3f3f; 27 const int MAXN = 1000 + 10; 28 struct Edge 29 { 30 int u,v,w,nxt; 31 Edge(int _u, int _v, int _w, int _nxt){u = _u;v = _v;w = _w;nxt = _nxt;} 32 Edge(){} 33 }edge1[MAXN * MAXN], edge2[MAXN * MAXN]; 34 int head1[MAXN], cnt1, head2[MAXN], cnt2; 35 inline void insert1(int a, int b, int c){edge1[++cnt1] = Edge(a,b,c,head1[a]), head1[a] = cnt1;} 36 inline void insert2(int a, int b, int c){edge2[++cnt2] = Edge(a,b,c,head2[a]), head2[a] = cnt2;} 37 struct Node 38 { 39 int u,w; 40 Node(int _u, int _w){u = _u;w = _w;} 41 Node(){} 42 }; 43 struct cmp 44 { 45 bool operator()(Node a, Node b) 46 { 47 return a.w > b.w; 48 } 49 }; 50 std::priority_queue<Node, std::vector<Node>, cmp> q; 51 int n,m,d[MAXN],vis[MAXN],tmp1,tmp2,tmp3,dp[MAXN]; 52 void dij(int S) 53 { 54 memset(d, 0x3f, sizeof(d)), d[S] = 0, memset(vis, 0, sizeof(vis)), q.push(Node(S, 0)); 55 while(q.size()) 56 { 57 Node now = q.top();q.pop(); 58 if(vis[now.u]) continue;vis[now.u] = 1; 59 for(int pos = head1[now.u];pos;pos = edge1[pos].nxt) 60 { 61 int v = edge1[pos].v; 62 if(vis[v]) continue; 63 if(d[v] > d[now.u] + edge1[pos].w) d[v] = d[now.u] + edge1[pos].w, q.push(Node(v, d[v])); 64 } 65 } 66 } 67 int Dp(int x) 68 { 69 if(vis[x]) return dp[x]; 70 for(int pos = head2[x];pos;pos = edge2[pos].nxt) 71 { 72 int v = edge2[pos].v; 73 dp[x] += Dp(v); 74 } 75 vis[x] = 1; 76 return dp[x]; 77 } 78 int main() 79 { 80 while(scanf("%d", &n) != EOF && n) 81 { 82 read(m), memset(head1, 0, sizeof(head1)), memset(head2, 0, sizeof(head2)), cnt1 = 0, cnt2 = 0; 83 for(int i = 1;i <= m;++ i) read(tmp1), read(tmp2), read(tmp3), insert1(tmp1, tmp2, tmp3), insert1(tmp2, tmp1, tmp3); 84 dij(2); 85 for(int i = 1;i <= cnt1;++ i) 86 if(d[edge1[i].v] < d[edge1[i].u]) 87 insert2(edge1[i].v, edge1[i].u, edge1[i].w); 88 memset(vis, 0, sizeof(vis)), memset(dp, 0, sizeof(dp)), vis[1] = 0, dp[1] = 1; 89 printf("%d\n", Dp(2)); 90 } 91 return 0; 92 }