Skip to content

Instantly share code, notes, and snippets.

@danielsaad
Last active August 29, 2015 14:24
Show Gist options
  • Save danielsaad/ce35a6aadb2ecdc96ec0 to your computer and use it in GitHub Desktop.
Save danielsaad/ce35a6aadb2ecdc96ec0 to your computer and use it in GitHub Desktop.
Código do problema Países em Guerra. Implementem o algoritmo de Dijkstra
#include <climits>
#include <iostream>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
const int infinity = INT_MAX;
const int BLACK = 2;
const int GREY = 1;
const int WHITE = 0;
using namespace std;
//return the sc component from node i
void dfs_sc(vector<vector<int>>& g,vector<vector<int>>& sc,int v, vector<int>& visited, vector<int>& index,vector<int>& low, int& dfs_n){
static stack<int> s;
index[v] = dfs_n;
low[v] = dfs_n;
dfs_n++;
s.push(v);
visited[v] = GREY;
for(int u=1;u<g.size();u++){
if(g[v][u]>=0){
if(visited[u]==WHITE){
dfs_sc(g,sc,u,visited,index,low,dfs_n);
low[v] = min(low[v],low[u]);
}
else if(visited[u]==GREY){
low[v] = min(low[v],index[u]);
}
}
}
visited[v] = BLACK;
if(index[v]==low[v]){
vector<int> scc;
int w;
do{
w = s.top();
s.pop();
scc.push_back(w);
}while(w!=v);
sc.push_back(scc);
}
}
void strong_components(vector<vector<int>>& graph){
vector<int> visited(graph.size(),0);
vector<int> index(graph.size());
vector<int> low(graph.size());
vector<vector<int>> sc;
stack<int> s1;
stack<int> s2;
int dfs_n = 1;
for(int i=1;i<graph.size();i++){
if(visited[i]==WHITE){
//do a DFS searching for strong components
dfs_sc(graph,sc,i,visited,index,low,dfs_n);
}
}
for(int i=0;i<sc.size();i++){
for(int j=0;j<sc[i].size();j++){
for(int k=0;k<sc[i].size();k++){
graph[sc[i][j]][sc[i][k]] = 0;
graph[sc[i][k]][sc[i][j]] = 0;
}
}
}
}
int main(){
int n,e;
while(cin >> n >> e && (n || e)){
vector<vector<int>> graph(n+1,vector<int>(n+1,-1));
for(int i=0;i<e;i++){
int x,y,h;
cin >> x >> y >> h;
graph[x][y] = h;
}
strong_components(graph);
int k;
cin >> k;
for(int i=0;i<k;i++){
int o,k;
cin >> o >> k;
//djikstra(graph,o,k); IMPLEMENTE O DIJKSTRA
}
cout << "\n";
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment