Just a Graph Problem Code: JAG Codechef Solutions

 

Just a Graph Problem Code: JAG
Submit

Read problem statements in MandarinBengaliRussian, and Vietnamese as well.

You are given an undirected graph with N nodes (numbered 1 through N). For each valid i, the i-th node has a weight Wi. Also, for each pair of nodes i and j, there is an edge connecting these nodes if jiWjWi.

Find the number of connected components in this graph.

Input Format

  • The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
  • The first line of each test case contains a single integer N.
  • The second line contains N space-separated integers W1,W2,,WN.

Output Format

For each test case, print a single line containing one integer --- the number of connected components in the graph.

Constraints

  • 1T104
  • 1N105
  • |Wi|109 for each valid i
  • the sum of N over all test cases does not exceed 2105

Subtasks

Subtask #1 (30 points):

  • N103
  • the sum of N over all test cases does not exceed 2103

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 i=1 and j=2, we have 21=21, therefore there are no edges in the graph and there are two connected components.

Example case 2: For i=1 and j=2, we have 2112, therefore there is an edge between 1 and 2, 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