Just One Small Issue

#include<bits/stdc++.h>

using namespace std;

int main()
{
long n1,n2,n3,i,j,count=0,x=0,y=0,z=0,k=0;
cin>>n1>>n2>>n3;

 long a[n1],b[n2],c[n3];
 long flag[50000];

 for(i=0;i<n1;i++)
      cin>>a[i];
 for(i=0;i<n2;i++)
      cin>>b[i];
 for(i=0;i<n3;i++)
      cin>>c[i];

 while(x<n1&&y<n2&&z<n3)
 {
      if(a[x]==b[y]&&a[x]==c[z])
      {    //cout<<a[x]<<" "<<x<<" "<<y<<" "<<z<<" 4\n";
           flag[k++]=a[x];
           x++;
           y++;
           z++;
      }
      else if(a[x]==b[y])
      {   // cout<<a[x]<<" "<<x<<" "<<y<<" 1\n";
           flag[k++]=a[x];
                x++;
                y++;
      }
      else if(a[x]==c[z])
      {   // cout<<a[x]<<" "<<x<<" "<<z<<" 2\n";
           flag[k++]=a[x];
           x++;
           z++;
      }
      else if(b[y]==c[z])
      {   // cout<<b[y]<<" "<<y<<" "<<z<<" 3\n";
           flag[k++]=b[y];
           y++;
           z++;
      }
      else if(a[x]>b[y])
           y++;
      else if(a[x]<b[y])
           x++;
      else if(a[x]>c[z])
           z++;
      else if(a[x]<c[z])
           x++;
      else if(c[z]>b[y])
           y++;
      else if(c[z]<b[y])
           z++;
 }
 cout<<k<<"\n";
 for(i=0;i<k;i++)
      cout<<flag[k]<<"\n";

}

//according to me the value of a[x] or b[y] is not getting stored in flag;
//Value of k is getting updated