ZOJ 2864 多條最短路徑

好吧, 終於可以緩解下這兩天的想砍人的情緒了。開始錯了之後就跟別人討論——以爲是數據變態(後來某某學長的一句話更是令我們崩潰):這個小偷能 瞬間移動 or 讓時光倒流....(有點科幻了)。糾結了半天發先不是這個問題,因爲標程都跑不出這些數據來。

最後發現是沒加代碼中的“紅色部分”了(去掉這個,pcnt數組就亂了,除了起點之外,各個點的pcnt都會在求最短路徑裏被初始化):

我喜歡偷懶,喜歡用一些隱含的條件。比如初始化啦,還有這個函數遞歸邊界啦,能不指出就不指出。

好了,於是乎。。各種悲劇。

  1. //太恐怖了,發現之前貼上的代碼求最短路徑時多加了個循環
  2. //現在改回來了,時間頓時少了400ms多。
  3. #include <cstdio>
  4. #include <queue>
  5. #include <algorithm>
  6. using namespace std;
  7. const int INF = 10000002;
  8. const int MAXN = 1002;
  9. int g[MAXN][MAXN], vis[MAXN], dis[MAXN], isPath[MAXN], par[MAXN][MAXN], pcnt[MAXN];
  10. typedef pair<int, int> pii;
  11. priority_queue<pii, vector<pii>, greater<pii> > q;
  12. void dijkstra(int n, int s) {
  13. fill(vis+1, vis+n+1, 0);
  14. for(int i = 1; i <= n; i++) {
  15. dis[i] = INF;
  16. }
  17. dis[s] = 0;
  18. q.push(make_pair(dis[s], s));
  19. while(!q.empty()) {
  20. pii u = q.top();
  21. q.pop();
  22. int x = u.second;
  23. if(vis[x]) continue;
  24. vis[x] = 1;
  25. for(int y = 1; y <= n; y++) {
  26. if(!vis[y] && g[x][y]) {
  27. if(dis[y] > dis[x] + g[x][y]) { //除了起點外,所有的點都執行這快代碼
  28. dis[y] = dis[x]+g[x][y];
  29. pcnt[y] = 1;
  30. par[y][0] = x;
  31. q.push(make_pair(dis[y], y));
  32. }
  33. else if(dis[y] == dis[x] + g[x][y]){
  34. par[y][pcnt[y]++] = x;
  35. }
  36. }
  37. }
  38. }
  39. }
  40. void buildPar(int t, int s) {
  41. isPath[t] = 1;
  42. if(t == s) {
  43. return;
  44. }
  45. for(int i = 0; i < pcnt[t]; i++) {
  46. int x = par[t][i];
  47. if(!isPath[x]) {
  48. buildPar(x, s);
  49. }
  50. }
  51. return;
  52. }
  53. void buildRoute(int t, int s, int n) {
  54. //fill(pcnt+1, pcnt+n+1, 0);
  55. fill(isPath+1, isPath+n+1, 0);
  56. buildPar(t, s);
  57. }
  58. void query(int s, int qt, int &ans, int n) {
  59. for(int i = 1; i <= n; i++) {
  60. if(isPath[i]) {
  61. if(dis[i] == qt) {
  62. ans++;
  63. }
  64. else if(dis[i] > qt) {
  65. for(int j = 0; j < pcnt[i]; j++) {
  66. int t = par[i][j];
  67. if(dis[t] < qt){
  68. ans++;
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }
  75. int main() {
  76. int n, m, s, t, u, v, w, q, qt, cas = 0;
  77. while(scanf("%d%d%d%d", &n, &m, &s, &t) != EOF) {
  78. if(cas) {
  79. printf("/n");
  80. }
  81. else {
  82. cas = 1;
  83. }
  84. fill(g[1], g[n+1], 0);
  85. for(int k = 0; k < m; k++) {
  86. scanf("%d%d%d", &u, &v, &w);
  87. g[u][v] = g[v][u] = w;
  88. }
  89. dijkstra(n, s);
  90. buildRoute(t, s, n);
  91. scanf("%d", &q);
  92. for(int i = 0; i < q; i++) {
  93. scanf("%d", &qt);
  94. if(qt >= dis[t] || qt <= 0) {
  95. printf("1/n");
  96. continue;
  97. }
  98. int ans = 0;
  99. query(s, qt, ans, n);
  100. printf("%d/n", ans);
  101. }
  102. }
  103. return 0;
  104. }
發佈了40 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章