Good treatment to do the next problem .
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define MAX 10005
#define Node pair< int , int >
#define INF 1<<30
struct cmp {
bool operator() ( const Node &a , const Node &b ) {
return a.second > b.second;
}
};
vector< Node > ady[ MAX ]; vector<int> distancia[ MAX ];
bool visitado[ MAX ];
priority_queue< Node , vector<Node> , cmp > Q;
int V;
void init(){
for( int i = 0 ; i <= V ; ++i ){
for (int j = 0; j <= V; ++j){
distancia[i].push_back(INF);
}
visitado[ i ] = false;
}
}
void relajacion( int actual , int adyacente , int peso ,int inicial){
if( distancia[ inicial ][actual] + peso < distancia[ inicial][adyacente ] ){
distancia[ inicial][adyacente ] = distancia[ inicial ][actual] + peso;
Q.push( Node( adyacente , distancia[inicial][ adyacente ] ) );
}
}
void dijkstra( int inicial ){
init();
Q.push( Node( inicial , 0 ) );
distancia[ inicial ][inicial]=0;
int actual , adyacente , peso;
while( !Q.empty() ){
actual = Q.top().first;
Q.pop();
if( visitado[ actual ] ) continue;
visitado[ actual ] = true;
for( int i = 0 ; i < ady[ actual ].size() ; ++i ){
adyacente = ady[ actual ][ i ].first;
peso = ady[ actual ][ i ].second;
if( !visitado[ adyacente ] ){
relajacion( actual , adyacente , peso ,inicial);
}
}
}
}
int main(){
int origen, destino , peso , inicial;
int f;
while(cin>>f>>V){
vector <int> fire(f);
for(int i=0;i<f;i++){
scanf("%d",&fire[i]);
}
for (int i = 0; i < V; ++i){
scanf("%d %d %d" , &origen , &destino , &peso );
ady[ origen ].push_back( Node( destino , peso ) );
ady[ destino ].push_back( Node( origen, peso ) );
}
for (int i = 1; i <= V; ++i){
dijkstra(i);
}
int consulta=0;
int cont2=INF;
for (int i = 1; i <= V; ++i){
int cont=0;
int nuevo=INF;
fire.push_back(i);
for (int k = 1; k <= V; ++k){
nuevo=INF;
vector<int>::iterator it=find(fire.begin(),fire.end(),k);
if(it!=fire.end())continue;
for (int j = 0; j < fire.size(); ++j){
if(k!=fire[j]){
if(nuevo>distancia[k][fire[j]]){
nuevo=distancia[k][fire[j]];
}
}
}
if(nuevo==INF){
nuevo=0;
}
cont+=nuevo;
}
if(cont2>cont){
cont2=cont;
consulta=i;
}
fire.pop_back();
}
printf("%d",consulta);
return 0;
}
}
Which is inefficient because of the complexity O (f2 * i), and the memory it occupies, however, I think it's not all bad, but in the last part, if you could give me a help, beware I know that the solution is in a web, I just want a clue, that I've had a good time in this problem, or another approach, because I think that using some voracious algorithm could come out.