You are viewing a single comment's thread. Return to all comments →
code got timed out...please suggest improvements for a more efficient algorithm...thanks in advance! :)
int gcd(int a,int b){
if(a>b && b!=0) return gcd(a%b,b); if(b>a && a!=0) return gcd(a,b%a);
if(a==0) return b; else return a;
} int main(){ int n; int m; int q; scanf("%d %d %d",&n,&m,&q); int *a = malloc(sizeof(int) * n); for(int a_i = 0; a_i < n; a_i++){ scanf("%d",&a[a_i]); } int *b = malloc(sizeof(int) * m); for(int b_i = 0; b_i < m; b_i++){ scanf("%d",&b[b_i]); } for(int a0 = 0; a0 < q; a0++){ int r1; int c1; int r2; int c2; scanf("%d %d %d %d",&r1,&c1,&r2,&c2);
int matrix[n][m]; for(int i=0;i<n;i++) for(int j=0;j<m;j++) matrix[i][j]=gcd(a[i],b[j]); int distinct=1; int arr[(r2-r1+1)*(c2-c1+1)]; int k=0; for(int i=r1;i<=r2;i++){ for(int j=c1;j<=c2;j++){ arr[k]=matrix[i][j]-matrix[r1][c1]; k++; } } int j; for(int i=1;i<k;i++){ int temp=arr[i]; j=i-1; while(j>=0&&temp<arr[j]){ arr[j+1]=arr[j]; j--; arr[j+1]=temp; } } int max=0; distinct=1; for(int i=0;i<k;i++) if(arr[i]>max){ max=arr[i]; distinct++; } int minimum=0; for(int i=0;i<k;i++) if(arr[i]<minimum){ minimum=arr[i]; distinct++; } printf("%d\n",distinct); } return 0;
}
Seems like cookies are disabled on this browser, please enable them to open this website
GCD Matrix
You are viewing a single comment's thread. Return to all comments →
code got timed out...please suggest improvements for a more efficient algorithm...thanks in advance! :)
int gcd(int a,int b){
if(a>b && b!=0) return gcd(a%b,b); if(b>a && a!=0) return gcd(a,b%a);
} int main(){ int n; int m; int q; scanf("%d %d %d",&n,&m,&q); int *a = malloc(sizeof(int) * n); for(int a_i = 0; a_i < n; a_i++){ scanf("%d",&a[a_i]); } int *b = malloc(sizeof(int) * m); for(int b_i = 0; b_i < m; b_i++){ scanf("%d",&b[b_i]); } for(int a0 = 0; a0 < q; a0++){ int r1; int c1; int r2; int c2; scanf("%d %d %d %d",&r1,&c1,&r2,&c2);
}