結果

問題 No.3650 Teleportation Cycles
コンテスト
ユーザー GOTKAKO
提出日時 2026-08-28 21:25:52
言語 C++17
(gcc 15.2.0 + boost 1.90.0)
コンパイル:
g++-15 -O2 -lm -std=c++17 -Wuninitialized -DONLINE_JUDGE -o a.out _filename_
実行:
./a.out
結果
AC  
実行時間 39 ms / 2,000 ms
+ 149µs
コード長 1,286 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 1,377 ms
コンパイル使用メモリ 222,172 KB
実行使用メモリ 27,592 KB
最終ジャッジ日時 2026-08-28 21:27:19
合計ジャッジ時間 3,698 ms
ジャッジサーバーID
(参考情報)
judge2_0 / judge1_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 36
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

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

pair<vector<int>,vector<vector<int>>> FunctionalGraph(const vector<int> &A){
    //N頂点N辺有向出次数全て1のグラフでreturn{cycle所属番号(-1は未所属),cycle頂点集合}.
    int N = A.size(),nowc = 0;
    vector<int> belong(N,-1);
    vector<vector<int>> cycle;
    vector<bool> already(N),visited(N);
    for(int i=0; i<N; i++){
        if(already.at(i)) continue;
        int pos = i;
        bool check = true;
        while(!visited.at(pos)) visited.at(pos) = true,pos = A.at(pos);
        if(already.at(pos)) check = false;
        int memo = pos;
        pos = i;
        while(!already.at(pos)) already.at(pos) = true,pos = A.at(pos);
        if(!check) continue;
 
        pos = memo;
        vector<int> now = {pos};
        belong.at(pos) = nowc; pos = A.at(pos);
        while(pos != memo) now.push_back(pos),belong.at(pos) = nowc,pos = A.at(pos);
        cycle.emplace_back(now),nowc++;
    }
    return {belong,cycle};
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
 
    int N; cin >> N;
    vector<int> A(N);
    for(auto &a : A) cin >> a,a--;
    auto [belong,cycle] = FunctionalGraph(A);
    int answer = 0;
    for(auto &c : cycle) answer++;
    cout << answer << endl;
}
0