最短路計數

來源:互聯網
上載者:User

#include<stdio.h><br />#include<iostream><br />#include<string.h><br />#include<queue><br />#include<set><br />#include<math.h><br />using namespace std;<br />#define N 1008<br />#define inf 0x7ffffff<br />struct node {<br /> int e, d;<br /> node(int a, int b) : e(a), d(b) {}<br /> bool operator<(const node & a)const {return d > a.d;}<br />};<br />vector <node> g[N];<br />int dis[N];<br />int cnt[N];<br />int n, m, s, t;<br />void dijkstra() {<br /> int i, j;<br /> priority_queue <node> q;<br /> memset(cnt, 0, sizeof (cnt));<br /> for (i = 0; i <= n; i++) dis[i] = inf;<br /> dis[s] = 0;<br /> cnt[s] = 1;<br /> q.push(node(s, 0));<br /> while (!q.empty()) {<br /> node p = q.top();<br /> q.pop();<br /> int k = p.e, d = p.d;<br /> if (dis[k] != d) continue;<br /> for (j = 0; j < g[k].size(); j++) {<br /> int e = g[k][j].e;<br /> int dist = g[k][j].d + d;<br /> if ((dis[e] > dist)) { /*新值小於最短路*/<br /> dis[e] = dist;<br /> cnt[e] = cnt[k];<br /> q.push(node(e, dist));<br /> continue;<br /> }<br /> if (dis[e] == dist) { /*新值等於最短路*/<br /> cnt[e] += cnt[k];<br /> continue;<br /> }<br /> }<br /> }<br />}<br />int main() {<br /> int tc;<br /> scanf("%d", &tc);<br /> while (tc--) {<br /> scanf("%d%d", &n, &m);<br /> for (int i = 0; i <= n; i++)<br /> g[i].clear();<br /> for (int i = 0; i < m; i++) {<br /> int a, b, c;<br /> scanf("%d%d%d", &a, &b, &c);<br /> g[a].push_back(node(b, c));<br /> //g[b].push_back(node(a, c));<br /> }<br /> scanf("%d%d", &s, &t);<br /> dijkstra();<br /> int ans = cnt[t];<br /> printf("%d/n", ans);<br /> }<br /> return 0;<br />}<br />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.