fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <queue>
  4.  
  5. using namespace std;
  6.  
  7. const int MOD = 1e9 + 7;
  8.  
  9. // vals is 1-indexed so vals[1] is the value of node 1
  10. vector<int> findOptimalShortestPaths(int n, int m, vector<int>& vals, vector<vector<int>>& edges) {
  11. // Build adjacency list
  12. vector<vector<int>> adj(n + 1);
  13. for (auto& edge : edges) {
  14. adj[edge[0]].push_back(edge[1]);
  15. adj[edge[1]].push_back(edge[0]);
  16. }
  17.  
  18. // State arrays
  19. vector<int> dist(n + 1, 1e9); // Shortest distance
  20. vector<int> max_fives(n + 1, -1); // Maximum 5s on a shortest path
  21. vector<int> ways(n + 1, 0); // Number of optimal paths
  22.  
  23. // Initialize source node (Node 1)
  24. dist[1] = 0;
  25. max_fives[1] = (vals[1] == 5 ? 1 : 0);
  26. ways[1] = 1;
  27.  
  28. queue<int> q;
  29. q.push(1);
  30.  
  31. // Standard BFS
  32. while (!q.empty()) {
  33. int u = q.front();
  34. q.pop();
  35.  
  36. for (int v : adj[u]) {
  37. int current_fives = max_fives[u] + (vals[v] == 5 ? 1 : 0);
  38.  
  39. // Case 1: First time reaching node v (Strictly shorter path)
  40. if (dist[u] + 1 < dist[v]) {
  41. dist[v] = dist[u] + 1;
  42. max_fives[v] = current_fives;
  43. ways[v] = ways[u];
  44. q.push(v);
  45. }
  46. // Case 2: Reaching node v via another shortest path
  47. else if (dist[u] + 1 == dist[v]) {
  48. if (current_fives > max_fives[v]) {
  49. // Found a path with the same length but more 5s
  50. max_fives[v] = current_fives;
  51. ways[v] = ways[u];
  52. } else if (current_fives == max_fives[v]) {
  53. // Found a path with the same length AND same number of 5s
  54. ways[v] = (ways[v] + ways[u]) % MOD;
  55. }
  56. }
  57. }
  58. }
  59.  
  60. // Prepare the final result for nodes 1 to n
  61. vector<int> result(n);
  62. for(int i = 1; i <= n; ++i) {
  63. result[i-1] = ways[i];
  64. }
  65.  
  66. return result;
  67. }
  68.  
  69. int main() {
  70. // Fast I/O
  71. ios_base::sync_with_stdio(false);
  72. cin.tie(NULL);
  73.  
  74. int n, m;
  75. if (!(cin >> n >> m)) return 0;
  76.  
  77. // vals is 1-indexed as required by your function
  78. vector<int> vals(n + 1);
  79. for (int i = 1; i <= n; ++i) {
  80. cin >> vals[i];
  81. }
  82.  
  83. vector<vector<int>> edges(m, vector<int>(2));
  84. for (int i = 0; i < m; ++i) {
  85. cin >> edges[i][0] >> edges[i][1];
  86. }
  87.  
  88. vector<int> result = findOptimalShortestPaths(n, m, vals, edges);
  89.  
  90. // Print the number of optimal paths to each node
  91. for (int i = 0; i < n; ++i) {
  92. cout << result[i] << (i == n - 1 ? "" : " ");
  93. }
  94. cout << "\n";
  95.  
  96. return 0;
  97. }
Success #stdin #stdout 0.01s 5320KB
stdin
8 8 
0 5 5 0 0 5 5 5 
1 2
2 3 
3 4 
4 5 
1 6
6 7
7 8 
8 5
stdout
1 1 1 1 1 1 1 1