# PROBLEM LINK:

Practice

Contest: Division 1

Contest: Division 2

Contest: Division 3

* Author:* Kumar Angesh Singh

*Anay Karnik*

**Tester:***Mohan Abhyas*

**Editorialist:**# DIFFICULTY:

Simple

# PREREQUISITES:

None

# PROBLEM:

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

Find the number of connected components in this graph.

# Hint:

## Hint

j - i \neq W_j - W_i can be rewritten as W_i - i \neq W_j - j.

# EXPLANATION:

Letâ€™s say W_i^1 = W_i - i. There is an edge between node i and node j if W_i^1 \neq W_j^1.

### Case 1 All W_i^1 are equal

All W_i^1 are equal => no edges exist => no of connected components = N

### Case 2 All W_i^1 are not equal

All W_i^1 are not equal => there exist i and j such that W_i^1 \neq W_j^1 => i and j are connected by edge. Consider any node k, it will be connected to atleast one of i, j(W_k^1 = W_i^1 => W_k^1 \neq W_j^1).

i, j are connected and every other node is connected to one of them => it is a connected graph => no of connected components = 1

# TIME COMPLEXITY:

\mathcal{O}(N) or \mathcal{O}(Nlog(N)) per testcase as per the implementation.

# SOLUTIONS:

## Setter's Solution

```
#include <bits/stdc++.h>
using namespace std;
signed main(){
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int T=1;
cin>>T;
while(T--){
int n;
cin>>n;
int w[n];
for(int i=0;i<n;i++){
cin>>w[i];
}
bool flag=1;
for(int i=1;i<n;i++){
if(w[0]!=w[i]-i){
flag=0;
break;
}
}
if(flag==0){
cout<<"1\n";
}
else{
cout<<n<<'\n';
}
}
return 0;
}
```

## Tester's Solution

```
#include <iostream>
#include <set>
#define int long long
signed main() {
std::ios::sync_with_stdio(false);
std::cin.tie(0);
int t;
std::cin >> t;
while(t--) {
int n;
std::cin >> n;
std::set<int> set;
for(int i = 0; i < n; i++) {
int x;
std::cin >> x;
set.insert(x-i);
}
if(set.size() == 1)
std::cout << n << std::endl;
else
std::cout << 1 << std::endl;
}
return 0;
}
```