GRL_3_B Bridges

Calendar Clock iconCalendar Clock icon

AOJ

Table of contents

# Problem

http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_3_B

# Computational complexity

O(V+E)O(V+E)

# Solution

// C++ 14
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <math.h>

#define ll long long
#define Int int
#define loop(x, start, end) for(Int x = start; x < end; x++)
#define loopdown(x, start, end) for(int x = start; x > end; x--)
#define rep(n) for(int x = 0; x < n; x++)
#define span(a,x,y) a.begin()+x,a.begin()+y
#define span_all(a) a.begin(),a.end()
#define len(x) (x.size())
#define last(x) (*(x.end()-1))

using namespace std;

#define MAX_V 10000

vector<Int> graph[MAX_V];
bool used_v[MAX_V],used_e[MAX_V][MAX_V];
Int ord[MAX_V],lowlink[MAX_V];
Int k=0;
vector<pair<Int, Int> > bridges;

bool compare (pair<Int, Int> a, pair<Int, Int> b) {
  if (a.first != b.first)  return a.first < b.first;
  if (a.second != b.second) return a.second < b.second;
  return false;
}

void dfs(Int v, Int parent) {
  used_v[v] = true;
  ord[v]=lowlink[v]=k++;
  
  for (Int u: graph[v]) {
    if(!used_v[u]) {
      used_e[v][u] = true;
      dfs(u, v);
      lowlink[v] = min(lowlink[v], lowlink[u]);
      if (ord[v] < lowlink[u]) {
        if (v < u) bridges.push_back(make_pair(v, u));
        else bridges.push_back(make_pair(u, v));
      }
    }
    else if(!used_e[u][v]) {
      lowlink[v] = min(lowlink[v], ord[u]);
    }
  }
}

Int main(void) {
  Int n, e, u, v;
  cin >> n >> e;
  loop(i,0,e) {
    cin >> u >> v;
    graph[u].push_back(v);
    graph[v].push_back(u);
  }
  dfs(0, -1);
  sort(bridges.begin(), bridges.end(), compare);
  for (auto b: bridges) cout << b.first << ' ' << b.second << endl;
}

Remote freelancer. A web and mobile application enginner.
Traveling around the world based on East Asia.
I'm looking forward to your job offers from all over the world!

Offer jobs or contact me!

Comments