fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int longestCommonSubarray(vector<vector<int>> &arr,int m,int n){ // arr is the array of size m*n
  4. int index[m][n+1];
  5. // Create an index array, so that we can access index of any element in a row in O(1) time.
  6. for(int i=0;i<m;i++)for(int j=0;j<n;j++)index[i][arr[i][j]]=j;
  7.  
  8. int l=1,max_length=1; // There will be atleast one element in the subarray. So, max_length will be atleast one.
  9. for(int i=1;i<n;i++){
  10. int curr_element=arr[0][i];
  11. int prev_element=arr[0][i-1];
  12. bool flag=0;
  13. for(int j=1;j<m;j++){
  14. if(index[j][prev_element]+1!=index[j][curr_element]){ // check whether current element is next to the previous element in the jth row
  15. flag=1;
  16. break;
  17. }
  18. }
  19. if(flag){ // If flag is true ,then there will be atleast one row where the current element is not immediate next to the previous element .
  20. l=1;
  21. }
  22. else l++;
  23. max_length=max(max_length,l);
  24. }
  25. return max_length;
  26. }
  27. void solve(){
  28. int n,m;
  29. cin>>m>>n;
  30. vector<vector<int>> arr(m,vector<int> (n));
  31. for(int i=0;i<m;i++)for(int j=0;j<n;j++)cin>>arr[i][j];
  32. cout<<longestCommonSubarray(arr,m,n);
  33.  
  34. }
  35. int main(){
  36. int tc;
  37. cin>>tc;
  38. while(tc--){
  39. solve();
  40. cout<<"\n";
  41. }
  42. }
Runtime error #stdin #stdout 0.65s 2095888KB
stdin
Standard input is empty
stdout
Standard output is empty