problemscpp
A collection of my answers to algorithm problems in c++.
函数
acwing::acwing849_408 命名空间参考

  1. Dijkstra求最短路 I
更多...

函数

int main (istream &cin, ostream &cout)
 
 TEST (acwing849_408, case1)
 
 TEST (acwing849_408, case2)
 

详细描述

  1. Dijkstra求最短路 I

函数说明

◆ main()

int acwing::acwing849_408::main ( istream &  cin,
ostream &  cout 
)

在文件 acwing408.cpp764 行定义.

764 {
765 int n, m;
766 cin >> n >> m;
767 unordered_map<int, unordered_map<int, int>> g = unordered_map<int, unordered_map<int, int>>();
768 unordered_set<int> visited = unordered_set<int>();
769 while(m--) {
770 int x, y, z;
771 cin >> x >> y >> z;
772 if(g[x].count(y) == 0 || g[x][y] > z) {
773 g[x][y] = z;// Only keep the smallest weight for multiple edges
774 }
775 }
776 visited.insert(1);
777 // Custom comparator for priority_queue to prioritize smaller weights
778 auto cmp = [](pair<int, int> left, pair<int, int> right) {
779 return left.second > right.second;// Compare by distance
780 };
781 priority_queue<pair<int, int>, vector<pair<int, int>>, decltype(cmp)> pq(cmp);
782 pq.emplace(1, 0);
783 while(!pq.empty()) {
784 auto [u, d] = pq.top();
785 pq.pop();
786 if(u != 1 && (visited.find(u) != visited.end()))
787 continue;
788 visited.insert(u);
789 if(u == n) {
790 cout << d;
791 return 0;
792 }
793 for(auto [v, w]: g[u]) {
794 if(visited.find(v) != visited.end())
795 continue;
796 pq.emplace(v, d + w);
797 }
798 }
799 cout << -1;
800 return 0;
801 }
bool cmp(const pair< int, int > &a, const pair< int, int > &b)
Definition: acwing.cpp:6470

引用了 acwing::acwing4397::cmp(), acwing::acwing1929::left , 以及 acwing::acwing1929::right.

被这些函数引用 TEST().

◆ TEST() [1/2]

acwing::acwing849_408::TEST ( acwing849_408  ,
case1   
)

在文件 acwing408_test.cpp1150 行定义.

1150 {
1151 istringstream in("3 3\n"
1152 "1 2 2\n"
1153 "2 3 1\n"
1154 "1 3 4");
1155 auto out = ostringstream();
1156 main(in, out);
1157 const auto ans = out.str();
1158 ASSERT_EQ("3", ans);
1159 }
int main(int argc, char **argv)
Definition: main.cpp:5

引用了 main().

◆ TEST() [2/2]

acwing::acwing849_408::TEST ( acwing849_408  ,
case2   
)

在文件 acwing408_test.cpp1161 行定义.

1161 {
1162 istringstream in("5 10\n"
1163 "1 2 2\n"
1164 "5 3 3\n"
1165 "4 1 8\n"
1166 "2 4 3\n"
1167 "4 5 7\n"
1168 "5 2 3\n"
1169 "3 4 1\n"
1170 "1 2 9\n"
1171 "3 2 3\n"
1172 "1 2 8");
1173 auto out = ostringstream();
1174 main(in, out);
1175 const auto ans = out.str();
1176 ASSERT_EQ("12", ans);
1177 }

引用了 main().