Just a Graph Problem Code: JAG Codechef Solutions
Just a Graph Problem Code: JAGSubmit
Read problem statements in Mandarin, Bengali, Russian, and Vietnamese as well.
You are given an undirected graph with nodes (numbered through ). For each valid , the -th node has a weight . Also, for each pair of nodes and , there is an edge connecting these nodes if .
Find the number of connected components in this graph.
Input Format
- The first line of the input contains a single integer denoting the number of test cases. The description of test cases follows.
- The first line of each test case contains a single integer .
- The second line contains space-separated integers .
Output Format
For each test case, print a single line containing one integer --- the number of connected components in the graph.
Constraints
- for each valid
- the sum of over all test cases does not exceed
Subtasks
Subtask #1 (30 points):
- the sum of over all test cases does not exceed
Subtask #2 (70 points): original constraints
Sample Input 1
2
2
1 2
2
2 1
Sample Output 1
2
1
Explanation
Example case 1: For and , we have , therefore there are no edges in the graph and there are two connected components.
Example case 2: For and , we have , therefore there is an edge between and , the graph is connected, so there is only one connected component.
Solution in C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
int main(){
ll t;cin>>t;
while(t--){
ll n;cin>>n;
ll a[n];
ll ans=0;
map<int,int> mp;
for(int i=0;i<n;i++){
cin>>a[i];
mp[a[i]-i-1]++;
if(mp[a[i]-i-1]==1){
ans++;
}
}
if(mp[a[0]-1]==n){
cout<<n<<endl;
}
else{
cout<<1<<endl;
}
}
return 0;
}
Comments
Post a Comment