why i am getting wrong answer for CHEFBM ques

#include<stdio.h>
#include<stdlib.h>

struct sort {
long long int a;
long long int b;
};

long long int compare(struct sort *p , struct sort * q) {
if(p->a != q->a ) return ( p->a - q->a ) ;
else return ( q->b - p->b ) ;
}

void go(long long int r[],long long int m) {
long long int i;
for(i=0;i<m;i++) r[i]=i+1;
}

int main () {
long long int n,m,p,i,c=0;
scanf("%lld%lld%lld",&n,&m,&p);
struct sort arr[p];
long long int q[n],r[m];

for(i=0;i<p;i++) scanf("%lld%lld",&arr[i].a,&arr[i].b);

qsort(arr , p , sizeof(struct sort) , compare ) ;

for(i=0;i<n;i++) q[i]=m-1;

go(r,m);
if(m!=1) {

for(i=1;i<p;i++) {
	
	if(arr[i].a==arr[i-1].a) {
		c++;
		if(c==1) {
			if(arr[i-1].b==m) { 
				r[arr[i-1].b-1]=r[arr[i-1].b-1]+1; q[arr[i-1].a-1]=q[arr[i-1].a-1]+1;}
				else if(arr[i-1].b==1) {
					r[arr[i-1].b-1]=r[arr[i-1].b-1]+1; if(r[arr[i-1].b-1]-r[arr[i-1].b]<=0)
					q[arr[i-1].a-1]=q[arr[i-1].a-1]-1;
					else q[arr[i-1].a-1]=-1;}
					else { r[arr[i-1].b-1]=r[arr[i-1].b-1]+1;
					if(r[arr[i-1].b-1]-r[arr[i-1].b]>0) q[arr[i-1].a-1]=-1;
					}}
			if(arr[i].b==m) {
				r[arr[i].b-1]=r[arr[i].b-1]+1; q[arr[i].a-1]=q[arr[i].a-1]+1; }
				else if(arr[i].b==1) {
					r[arr[i].b-1]=r[arr[i].b-1]+1; if(r[arr[i].b-1]-r[arr[i].b]<=0)
					q[arr[i].a-1]=q[arr[i].a-1]-1;
					else q[arr[i].a-1]=-1;}
					else { r[arr[i].b-1]=r[arr[i].b-1]+1;
					if(r[arr[i].b-1]-r[arr[i].b]>0) q[arr[i].a-1]=-1;
					}}
	else {
		if(c==0) {
			if(arr[i-1].b==m) {
				r[arr[i-1].b-1]=r[arr[i-1].b-1]+1; q[arr[i-1].a-1]=q[arr[i-1].a-1]+1;}
				else if(arr[i-1].b==1) {
					r[arr[i-1].b-1]=r[arr[i-1].b-1]+1;  if(r[arr[i-1].b-1]-r[arr[i-1].b]<=0)
					q[arr[i-1].a-1]=q[arr[i-1].a-1]-1;
					else q[arr[i-1].a-1]=-1;}
					else { r[arr[i-1].b-1]=r[arr[i-1].b-1]+1;
					if(r[arr[i-1].b-1]-r[arr[i-1].b]>0) q[arr[i-1].a-1]=-1;
					}}
					go(r,m);
					c=0;
		}}
		
	go(r,m);
	if(c==0) {
		if(arr[i-1].b==m) {
				r[arr[i-1].b-1]=r[arr[i-1].b-1]+1; q[arr[i-1].a-1]=q[arr[i-1].a-1]+1;}
				else if(arr[i-1].b==1) {
					r[arr[i-1].b-1]=r[arr[i-1].b-1]+1; if(r[arr[i-1].b-1]-r[arr[i-1].b]<=0)
					q[arr[i-1].a-1]=q[arr[i-1].a-1]-1;
					else q[arr[i-1].a-1]=-1;}
					else { r[arr[i-1].b-1]=r[arr[i-1].b-1]+1;
					if(r[arr[i-1].b-1]-r[arr[i-1].b]>0) q[arr[i-1].a-1]=-1;
					}}}
	
	for(i=0;i<n;i++) printf("%lld\n",q[i]);
	return 0;

}

You code is quite complex and I couldn’t gather courage to go through it. However you can go over this question - http://discuss.codechef.com/questions/42668/chef-and-strange-matrix?page=1#42672. Here I’ve discussed my approach to solve this problem which is pretty straightforward and easy to understand.

Moreover I can see you are sorting the values which are not at all required to solve this problem. Hope this helped :slight_smile:

//