There are many spots for parking the shared bicycles in Hangzhou. When some of the bicycles are broken, the management center will receive a message for sending a truck to collect them. Now given the map of city, you are supposed to program the collecting route for the truck. The strategy is a simple greedy method: the truck will always move to the nearest spot to collect the broken bicycles. If there are more than one nearest spot, take the one with the smallest index.
Input Specification:
Each input file contains one test case. For each case, the first line contains two positive integers: N (≤ 200), the number of spots (hence the spots are numbered from 1 to N, and the management center is always numbered 0), and M, the number of streets connecting those spots. Then M lines follow, describing the streets in the format:
S1 S2 Dist
where S1
and S2
are the spots at the two ends of a street, and Dist
is the distance between them, which is a positive integer no more than 1000. It is guaranteed that each street is given once and S1
is never the same as S2
.
Output Specification:
For each case, first print in a line the sequence of spots in the visiting order, starting from 0. If it is impossible to collect all the broken bicycles, output in the second line those spots that cannot be visited, in ascending order of their indices. Or if the job can be done perfectly, print in the second line the total moving distance of the truck.
All the numbers in a line must be separated by 1 space, and there must be no extra space at the beginning or the end of the line.
Sample Input 1 (shown by the figure below):
7 10
0 2 1
0 4 5
0 7 3
0 6 4
0 5 5
1 2 2
1 7 2
2 3 4
3 4 2
6 7 9
Sample Output 1:
0 2 1 7 6 3 4 5
33
Sample Input 2:
7 8
0 2 1
0 4 5
0 7 3
1 2 2
1 7 2
2 3 4
3 4 2
6 5 1
Sample Output 2:
0 2 1 7 3 4
5 6
#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
const int N = 210,INF = 0x3f3f3f3f;
int dist[N][N];
bool st[N];
int n,m;
void floyd(){
for(int k = 0;k<=n;k++)
for(int i = 0;i<=n;i++)
for(int j = 0;j<=n;j++)
dist[i][j] = min(dist[i][j],dist[i][k]+dist[k][j]);
}
int flag = 1;
int sum = 0;
vector<int> miss;
void dfs(int u){
if(flag)flag = 0;
else printf(" ");
printf("%d",u);
st[u] = 1;
int k = -1;
for(int i = 1;i<=n;i++){
if(!st[i]&&dist[u][i]!=INF){
if(k==-1||dist[u][i]<dist[u][k])k = i;
}
}
if(k==-1) return;
sum+=dist[u][k];
dfs(k);
}
int main(){
scanf("%d %d",&n,&m);
memset(dist,0x3f,sizeof dist);
for(int i = 0;i<=n;i++) dist[i][i] = 0;
for(int i = 0;i<m;i++){
int a,b,c;cin>>a>>b>>c;
dist[a][b] = dist[b][a] = min(dist[a][b],c);
}
floyd();
dfs(0);
for(int i = 0;i<=n;i++){
if(!st[i])miss.push_back(i);
}
puts("");
if(miss.empty()){
cout<<sum<<endl;
}
else{
cout<<miss[0];
for(int i = 1;i<miss.size();i++)cout<<" "<<miss[i];
}
}