华为笔试:N度好友

 

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 bool cmp(pair<int,int> a, pair<int,int> b){
 5     if(a.second > b.second) return 1;
 6     if(a.second==b.second) return a.first < b.first;
 7     return 0;
 8 }
 9 
10 int main(){
11     int t;
12     cin>>t;
13     while(t--){
14         int m,i,n;
15         cin>>m>>i>>n;
16         int k;
17         cin>>k;
18         
19         vector<vector<int> > graph( m, vector<int>(m,0) );
20         int ki,kj,kw;
21         for(int i=0; i<k; i++){
22             cin>>ki>>kj>>kw;
23             graph[ki][kj] = kw;
24             graph[kj][ki] = kw;
25         }
26         
27         vector<bool> visited(m,0); 
28         vector<int> friendly(m,-1);
29         queue<int> temp;
30         temp.push(i);
31         while(!temp.empty() ){
32             int size = temp.size();
33             while(size--){
34                 int cur = temp.front();
35                 temp.pop();
36                 visited[cur] = 1;
37                 for(int x=0; x<m; x++){
38                     if( !visited[x] && graph[cur][x] > 0 && friendly[x]==-1 ){
39                         friendly[x] = friendly[cur] + graph[cur][x];
40                         temp.push(x);
41                     }                     
42                 }            
43             }
44             
45             n--;
46             if(n==0) break;
47         }
48         
49         if(n!=0 || temp.empty()){
50             cout<<-1<<endl;
51             continue;
52         }
53         
54         vector<pair<int,int> > res;
55         
56         map<int,int> exist;
57         while(!temp.empty()){
58             exist[ temp.front() ]  = friendly[ temp.front() ];
59             temp.pop();         
60         } 
61         res.assign(exist.begin(), exist.end() );
62         
63         sort(res.begin(), res.end(), cmp);
64         for(int p=0;p<res.size(); p++){
65             cout<<res[p].first<<" "; 
66         }
67         cout<<endl;
68         
69     }
70     
71 }

 

posted on 2019-09-08 23:19  逸阳  阅读(975)  评论(1编辑  收藏  举报

导航