65,206
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <vector>
#include <map>
#include <set>
#include <string>
#include <algorithm>
#include <limits>
using namespace std;
int kthcity(int ncity, int nroad, int roads[], int k)
{
typedef vector <pair <int, int> > roads_t;
typedef map <int, roads_t> full_map_t;
typedef map <int, int> solved_t;
full_map_t full_map;
solved_t solved;
int solved_count = 0;
// prepare map
for(int i = 0; i < nroad; i++) {
int end1 = roads[i*3];
int end2 = roads[i*3+1];
int length = roads[i*3+2];
if(full_map.count(end1) > 0) {
full_map[end1].push_back(make_pair(length, end2));
}
else {
roads_t roads;
roads.push_back(make_pair(length, end2));
full_map[end1] = roads;
}
if(full_map.count(end2) > 0) {
full_map[end2].push_back(make_pair(length, end1));
}
else {
roads_t roads;
roads.push_back(make_pair(length, end1));
full_map[end2] = roads;
}
}
for(full_map_t::iterator it = full_map.begin(); it != full_map.end(); it++) {
sort(it->second.begin(), it->second.end());
}
// search
solved[0] = 0;
int min_city = 0;
int min_path = 0;
while(solved_count < k) {
min_path = INT_MAX;
min_city = -1;
for(solved_t::const_iterator it = solved.begin(); it != solved.end(); it++) {
const roads_t &roads = full_map[it->first];
for(roads_t::const_iterator it2 = roads.begin(); it2 != roads.end(); it2++) {
if(solved.find(it2->second) == solved.end()) {
if(it2->first + it->second < min_path) {
min_path = it2->first + it->second;
min_city = it2->second;
}
break;
}
}
}
if(min_city < 0)
return -1;
solved_count++;
solved[min_city] = min_path;
}
return min_city;
}
int main()
{
int road_data[] = { 0, 1, 120, 0, 2, 180, 1, 3, 40 }; // test data1
cout << kthcity(4, 3, road_data, 3) << endl;
int road_data2[] = { 0, 1, 120, 0, 3, 60, 3, 2, 30}; // test data2
cout << kthcity(4, 3, road_data2, 1) << endl;
return 0;
}
编译运行没问题!