Hi i need help to solve this problem.
Anyone please suggest me the approach to sole this
Sort the sets, if y2 -y1 / x2 - x1 is constant then 2 else 0.
static boolean check_slope(long x1,long y1,long x2,long y2,long x3,long y3)
{
if( ((y2-y1)(x3-x2)) == ((y3-y2)(x2-x1)))
return true;
return false;
}
static boolean is_valid(int x[],int y[],int n)
{
for(int i=1;i<(n-1);i++)
if(!check_slope(x[i-1],y[i-1],x[i],y[i],x[i+1],y[i+1]))
return false;
return true;
}
I was doing this during contest . X and Y are sorted and checking for the equality of slopes between 3 consecutive points. I is_valid is true then ans is 2 otherwise ans will be 0 .Could you please tell me what is wrong in this
I don’t think long int is large enough to store 10^18
Could you please share link of your solution
Ok maybe I’m a bit wrong. You’ll have to check both forward and backward seperately.
#include <iostream>
#include <bits/stdc++.h>
#include <cmath>
#include <vector>
#define ll long long int
#define mp make_pair
#define pb push_back
#define vi vector<int>
using namespace std;
using namespace std::chrono;
long long int p=1e9 +7;
ll solve(){
int n;
cin>>n;
ll x[n];
ll y[n];
for(int i=0;i<n;i++){
cin>>x[i];
}
for(int i=0;i<n;i++){
cin>>y[i];
}
int ans=2;
sort(x,x+n);
sort(y,y+n);
ll ydiff=y[1]-y[0];
ll xdiff=x[1]-x[0];
for(int i=2;i<n;i++){
if( (y[i]-y[i-1])*xdiff != (x[i]-x[i-1])*ydiff ){
ans--;
break;
}
}
sort(y,y+n,greater<int>());
ydiff=y[1]-y[0];
for(int i=2;i<n;i++){
if( (y[i]-y[i-1])*xdiff != (x[i]-x[i-1])*ydiff ){
ans--;
break;
}
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >>t;
//t=1;
srand(time(0));
while(t--){
cout<<solve()<<"\n";
}
}
Got it , thanks .