답안 #1065378

# 제출 시각 아이디 문제 언어 결과 실행 시간 메모리
1065378 2024-08-19T06:47:58 Z vjudge1 공장들 (JOI14_factories) C++17
0 / 100
215 ms 98900 KB
#include "factories.h"
#include <bits/stdc++.h>
#define ll long long
#define pb push_back

using namespace std;

int up(int n1, int k);
void DFS(int n1);
void dijkstra(int n1);

ll inf = LONG_LONG_MAX;
int n;
vector<vector<pair<int, ll>>> adj(500005);
vector<bool> vis(500005, 0),vis1(500005, 0);
vector<ll> dis(500005, inf), h(500005,0), parent(500005,0);
vector<pair<ll,ll>> outdeg(500005,{0,0});
priority_queue<pair<ll, int>, vector<pair<ll, int>>, greater<pair<ll, int>>> pq;
vector<vector<int>> sparseT(500005, vector<int>(19,0));

void Init(int N, int A[], int B[], int D[])
{
  n = N;
  for (int i = 0; i < N - 1; i++)
  {
    adj[A[i]].pb({B[i], D[i]});
    adj[B[i]].pb({A[i], D[i]});
    outdeg[A[i]].first++;
    outdeg[A[i]].second = A[i];
    outdeg[B[i]].first++;
    outdeg[B[i]].second = B[i];
  }
  sort(outdeg.rbegin(),outdeg.rend());
  //cout<<outdeg[0].second<<endl;
  
  dijkstra(outdeg[0].second);
  parent[outdeg[0].second] = outdeg[0].second;
  DFS(outdeg[0].second);
  /*for(int i=0; i < N; i++){
    cout<<dis[i]<<", ";
  }*/
  cout<<endl;
  for(int i=0; i < N; i++){
    sparseT[i][0] = parent[i];
  }
  for(int j=1; j < 20; j++){
    for(int i=0; i < N; i++){
      sparseT[i][j] = parent[sparseT[i][j-1]];
    }
  }
}

long long Query(int S, int X[], int T, int Y[])
{
  ll ans = inf;
  for (int i = 0; i < S; i++){
    for(int j = 0; j < T; j++){
      int aux1=X[i],aux2=Y[j];
      while(h[aux1] > h[aux2]){
        aux1 = parent[aux1];
      }
      while(h[aux1] < h[aux2]){
        aux2 = parent[aux2];
      }
      if(aux1 == aux2){
        ans = min(ans,(dis[Y[j]]-dis[aux1]));
        continue;
      }
      for(int k = 1; k <= h[aux1]; k++){
        if(up(aux1,k) == up(aux2,k)){
          ans = min(ans,((dis[X[i]]-dis[up(aux1,k)])+(dis[Y[j]]-dis[up(aux1,k)])));
          break;
        }
      }
    }
  }

    cout<<"  ";
  return ans;
}

int up(int n1, int k){
  int act=n1;
  for(int p=0; p < 20; p++){
    if(k & (1<<p)){
      act = sparseT[act][p];
    }
  }

  return act;
}

void DFS(int n1){
  vis1[n1] = 1;

  for(auto [x,w]: adj[n1]){
    if(vis1[x])continue;
    h[x] = h[n1]+1;
    parent[x] = n1;
    DFS(x);
  }
}

void dijkstra(int n1)
{
  dis[n1] = 0;
  pq.push({0,n1});

  while (!pq.empty())
  {
    int a = pq.top().second;
    pq.pop();

    if (vis[a])
      continue;
    vis[a] = 1;

    for (auto [b, w] : adj[a])
    {
      if (dis[b] > dis[a] + w)
      {
        dis[b] = dis[a] + w;
        pq.push({dis[b], b});
      }
    }
  }
}
# 결과 실행 시간 메모리 Grader output
1 Incorrect 215 ms 97104 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 53 ms 98900 KB Output isn't correct
2 Halted 0 ms 0 KB -
# 결과 실행 시간 메모리 Grader output
1 Incorrect 215 ms 97104 KB Output isn't correct
2 Halted 0 ms 0 KB -