/ SeriousOJ /

Record Detail

Accepted


  
# Status Time Cost Memory Cost
#1 Accepted 1ms 532.0 KiB
#2 Accepted 670ms 16.637 MiB
#3 Accepted 242ms 13.727 MiB
#4 Accepted 182ms 13.645 MiB
#5 Accepted 52ms 8.324 MiB
#6 Accepted 447ms 2.195 MiB
#7 Accepted 95ms 532.0 KiB

Code

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;




void dfs(int vertex,vector<bool>&visited,vector<vector<int>>&graph,vector<int>&tempCC_Storage,vector<vector<int>>&connectedComponentsStorage){
    tempCC_Storage.push_back(vertex);
    visited[vertex]=true;
    for(auto child:graph[vertex]){
        if(visited[child])continue;
        dfs(child,visited,graph,tempCC_Storage,connectedComponentsStorage);
    }
}
vector<int> takeVectorInput(int n){
    

    vector<int>v(n+1);
   for(int i=1;i<=n;++i) {
    cin>>v[i];
   }
    return v;
}
int main(){
    int t;
    cin>>t;

    while(t--){
                int n,e;
            cin>>n>>e;
            auto v=takeVectorInput(n);
            vector<vector<int>> graph(n+1);
            vector<bool>visited(n+1,false);
            for(int i=0;i<e;++i){
                int n1,n2;
                cin>>n1>>n2;
                graph[n1].push_back(n2);
                graph[n2].push_back(n1);
            }
            vector<vector<int>> connectedComponentsStorage;
            int countOfComponents=0;
            for(int i=1;i<=n;++i){
                if(visited[i])continue;
                vector<int> tempCC_Storage;
                dfs(i,visited,graph,tempCC_Storage,connectedComponentsStorage);
                connectedComponentsStorage.push_back(tempCC_Storage);
                countOfComponents++;
            }
            // cout<<countOfComponents<<endl;
            int ans=0;
            for(auto components:connectedComponentsStorage){
                // vector<int> temp;
                map<int,int> mp;
                for(auto ele:components){
                    if(v[ele]==ele)continue;
                    mp[v[ele]]++;
                }
                int cnt=0;
                for(auto ele:components){
                    if(mp[ele])cnt++;
                }
                ans+=cnt;

                // cout<<endl;
            }
            for(int i=1;i<=n;++i){
                if(v[i]==i)ans++;
            }
            cout<<ans<<endl;
    }
    
}
// Sample input:
// 8 5
// 1 2
// 2 3
// 2 4
// 3 5
// 6 7

// Sample Output:
// 3

Information

Submit By
Type
Submission
Problem
P1119 Maximizing Fixed Points
Contest
Happy New Year 2025
Language
C++17 (G++ 13.2.0)
Submit At
2025-01-02 15:42:00
Judged At
2025-01-02 15:42:00
Judged By
Score
100
Total Time
670ms
Peak Memory
16.637 MiB