結果

問題 No.1865 Make Cycle
ユーザー simansiman
提出日時 2022-03-05 04:05:41
言語 C++17(clang)
(17.0.6 + boost 1.83.0)
結果
AC  
実行時間 1,480 ms / 3,000 ms
コード長 1,316 bytes
コンパイル時間 5,869 ms
コンパイル使用メモリ 110,360 KB
実行使用メモリ 18,064 KB
最終ジャッジ日時 2023-09-26 08:24:27
合計ジャッジ時間 24,670 ms
ジャッジサーバーID
(参考情報)
judge15 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 745 ms
13,808 KB
testcase_01 AC 431 ms
11,552 KB
testcase_02 AC 1,063 ms
14,504 KB
testcase_03 AC 586 ms
13,528 KB
testcase_04 AC 946 ms
15,752 KB
testcase_05 AC 98 ms
14,692 KB
testcase_06 AC 646 ms
13,660 KB
testcase_07 AC 874 ms
13,748 KB
testcase_08 AC 902 ms
16,200 KB
testcase_09 AC 101 ms
14,464 KB
testcase_10 AC 1,007 ms
15,836 KB
testcase_11 AC 894 ms
14,976 KB
testcase_12 AC 725 ms
13,728 KB
testcase_13 AC 863 ms
13,768 KB
testcase_14 AC 574 ms
12,316 KB
testcase_15 AC 1,014 ms
14,892 KB
testcase_16 AC 1,046 ms
15,748 KB
testcase_17 AC 93 ms
12,340 KB
testcase_18 AC 104 ms
15,192 KB
testcase_19 AC 1,480 ms
18,064 KB
testcase_20 AC 2 ms
4,380 KB
testcase_21 AC 2 ms
4,376 KB
testcase_22 AC 2 ms
4,376 KB
testcase_23 AC 2 ms
4,376 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <cassert>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <climits>
#include <map>
#include <queue>
#include <set>
#include <cstring>
#include <vector>

using namespace std;
typedef long long ll;

int N, Q;
int A[100010];
int B[100010];
map<int, map<int, bool>> E;

void update_edges(int x) {
  for (int i = 0; i < Q; ++i) {
    int a = A[i];
    int b = B[i];

    if (i < x) {
      E[a][b] = true;
    } else {
      E[a][b] = false;
    }
  }
}

bool dfs(int v, vector<int> &visited) {
  visited[v] = 1;

  for (auto &[u, s] : E[v]) {
    if (not s) continue;

    if (visited[u] == 1) return true;
    if (visited[u] == 0 && dfs(u, visited)) return true;
  }

  visited[v] = 2;
  return false;
}

bool has_cycle() {
  vector<int> visited(N + 1, 0);

  for (int v = 1; v <= N; ++v) {
    if (visited[v] == 0 && dfs(v, visited)) return true;
  }

  return false;
}

int main() {
  cin >> N >> Q;

  for (int i = 0; i < Q; ++i) {
    cin >> A[i] >> B[i];
  }

  update_edges(Q);
  if (not has_cycle()) {
    cout << -1 << endl;
    return 0;
  }

  int ok = Q;
  int ng = 0;

  while (abs(ok - ng) >= 2) {
    int x = (ok + ng) / 2;
    update_edges(x);

    if (has_cycle()) {
      ok = x;
    } else {
      ng = x;
    }
  }

  cout << ok << endl;

  return 0;
}
0