Cod sursa(job #2592116)

Utilizator isa_tudor_andreiAndrei Tudor isa_tudor_andrei Data 1 aprilie 2020 10:04:29
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("poligon7.in");
ofstream fout("poligon7.out");

const int NMAX = 2505;
const int MMAX = NMAX * NMAX;

struct Edge {
  int x;
  int y;
  long double cost;
}G[MMAX];

long double dist( pair<int,int> a, pair<int, int> b ) {
  long double r = (a.first - b.first) * (a.first - b.first) + (a.second - b.second) * (a.second - b.second);
  r = (long double)sqrt(r);
  return r;
}

int root[NMAX], rang[NMAX];
vector<pair<int,int>> arbore;
pair<int,int> v[NMAX];

bool cmp( Edge a, Edge b ) {
  return a.cost < b.cost;
}

bool cmp2( pair<int, int> a, pair<int, int> b ) {
  return abs(a.first - a.second) < abs(b.first - b.second);
}

int find_root( int x ) {
  int og = x;
  while( root[og] != og )
    og = root[og];
  while( root[x] != x ) {
    int oog = root[x];
    root[x] = og;
    x = oog;
  }
  return og;
}

void unite( int x, int y ) {
  if( rang[x] > rang[y] )
    root[y] = x;
  else
    root[x] = y;
  if( rang[x] == rang[y] )
    rang[y] ++;
}

void compute_APM( int n, int m, int cer ) {
  arbore.clear();
  sort(G + 1, G + m + 1, cmp);
  long double ans = 0;
  int k = 0;
  for( int i = 1; k <= n - 2; i ++ ) {
    int rootx = find_root(G[i].x);
    int rooty = find_root(G[i].y);
    if( rootx != rooty ) {
      k ++;
      ans += G[i].cost;
      unite(rootx, rooty);
      arbore.push_back({G[i].x,G[i].y});
    }
  }
  if( cer == 1 )
    fout<<setprecision(12)<<fixed<<ans<<"\n";
  else {
    sort(arbore.begin(), arbore.end(), cmp2);
    for( auto it : arbore )
      fout<<it.first<<" "<<it.second<<"\n";
  }
}

int main() {
    int cer, t;
    fin>>cer>>t;
    while( t -- ) {
      int n;
      fin>>n;
      for( int i = 1; i <= n; i ++ ) {
        fin>>v[i].first>>v[i].second;
        root[i] = i, rang[i] = 0;
      }
      int m = 0;
      for( int i = 1; i <= n; i ++ )
        for( int j = i + 1; j <= n; j ++ )
          G[++m] = {i, j, dist(v[i], v[j])};
      compute_APM(n, m, cer);
      memset(root, 0, sizeof(root));
      memset(rang, 0, sizeof(rang));
      memset(G, 0, sizeof(G));
    }
    return 0;
}