QOJ.ac

QOJ

IDProblemSubmitterResultTimeMemoryLanguageFile sizeSubmit timeJudge time
#282547#6847. Hide-And-Seek GamezlxFTHAC ✓1024ms3996kbC++171.9kb2023-12-12 12:54:032023-12-12 12:54:04

Judging History

你现在查看的是最新测评结果

  • [2023-12-12 12:54:04]
  • 评测
  • 测评结果:AC
  • 用时:1024ms
  • 内存:3996kb
  • [2023-12-12 12:54:03]
  • 提交

answer

#include <bits/stdc++.h>
using namespace std;

void exgcd(int a, int b, int &g, int &x, int &y) {
  if (!b) {
    g = a;
    x = 1, y = 0;
    return;
  }
  exgcd(b, a % b, g, y, x);
  y -= a / b * x;
}

const int N = 3e3 + 5;
int n, m;
vector<int> G[N], rs[2][N];

int tp, st[N], ins[N];
int da, db;
void dfs(int u, int tar, int s, int typ) {
  st[++tp] = u, ins[u] = 1;
  if (u == tar) {
    if (typ == 0 && !da) da = tp - 1;
    if (typ == 1 && !db) db = tp - 1; 
    for (int i = 1; i <= tp - 1; i++) {
      int v = st[i];
      rs[typ][v].push_back(s);
      s++;
    }
  } else {
    for (auto v : G[u]) if (!ins[v]) {
      dfs(v, tar, s, typ);
    }
  }
  ins[u] = 0, tp--;
}

void solve() {
  cin >> n >> m;
  for (int i = 1; i <= n; i++) {
    G[i].clear();
  }
  for (int i = 0; i < n - 1; i++) {
    int u, v;
    cin >> u >> v;
    G[u].push_back(v);
    G[v].push_back(u);
  }
  for (int i = 1; i <= m; i++) {
    int sa, ta, sb, tb;
    cin >> sa >> ta >> sb >> tb;
    da = 0;
    db = 0;
    dfs(sa, ta, 0, 0);
    dfs(sb, tb, 0, 1);
    dfs(ta, sa, da, 0);
    dfs(tb, sb, db, 1);
    int ans = 1e9, id;
    da *= 2;
    db *= 2;
    for (int u = 1; u <= n; u++) {
      for (auto x : rs[0][u]) for (auto y : rs[1][u]) {
        int c = y - x;
        int g, t, r;
        exgcd(da, db, g, t, r);
        if (c % g) continue;
        t *= c / g;
        t = (t % (db / g) + (db / g)) % (db / g);
        if (x + t * da < ans) {
          ans = x + t * da;
          id = u;
        }
      }
    }
    if (ans == int(1e9)) cout << -1 << "\n";
    else cout << id << "\n";
    for (int u = 1; u <= n; u++) {
      for (int j : {0, 1}) {
        rs[j][u].clear();
      }
    }
  }
}
int main() {
  cin.tie(0)->sync_with_stdio(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}

Details

Tip: Click on the bar to expand more detailed information

Test #1:

score: 100
Accepted
time: 1024ms
memory: 3996kb

input:

500
6 20
1 2
1 3
3 4
2 5
3 6
1 6 6 5
2 1 6 2
5 1 2 6
2 6 1 2
6 3 6 4
4 1 1 3
5 6 3 4
2 1 3 5
2 4 1 2
6 2 1 2
6 2 1 4
1 6 1 6
2 5 2 6
2 5 6 2
5 2 1 3
5 6 6 4
4 1 4 5
5 4 4 1
3 6 1 2
6 1 4 3
71 30
1 2
2 3
2 4
4 5
2 6
6 7
4 8
2 9
1 10
9 11
3 12
5 13
5 14
10 15
6 16
13 17
17 18
4 19
5 20
17 21
20 22
4 2...

output:

3
-1
-1
-1
6
3
-1
1
-1
1
3
1
2
-1
-1
3
4
1
-1
3
-1
11
2
-1
5
-1
17
-1
-1
5
-1
-1
-1
-1
2
-1
5
53
5
7
-1
-1
2
4
-1
-1
-1
-1
-1
-1
-1
5
-1
1
5
1
-1
-1
-1
-1
33
5
1
1
-1
1
-1
-1
-1
-1
7
-1
-1
9
5
3
-1
-1
-1
19
-1
-1
6
5
-1
-1
5
-1
-1
-1
-1
1
-1
7
-1
-1
1
-1
-1
-1
8
-1
13
-1
-1
-1
-1
4
5
-1
-1
5
-1
-1
8...

result:

ok 53199 lines