Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

鸟题,DFS水过

Posted by donkeyinacm at 2010-09-04 09:40:39 on Problem 3503
#include <iostream>
#define MAXRC 505

int M[MAXRC][MAXRC];
bool V[MAXRC][MAXRC];
int cas,R,C,D;
int dr[]={1,0,0,-1};
int dc[]={0,1,-1,0};
int vis[MAXRC][MAXRC];

bool check(int r,int c)
{
	return 1<=r && r<=R && 1<=c && c<=C;
}

void print()
{
	int r,c;
	for(r=1;r<=R;r++)
	{
		for(c=1;c<=C;c++)
			if(!V[r][c])
				printf("%c ",'*');
			else
				printf("%d ",M[r][c]);
		printf("\n");
	}
	printf("\n");
}

void dfs(int br,int bc,int v,bool &reached,int mask)
{
	vis[br][bc]=mask;
	V[br][bc]=false;
	int tr,tc,d;
	for(d=0;d<4;d++)
	{
		tr=br+dr[d];
		tc=bc+dc[d];
		if(check(tr,tc))
			if(v>=M[tr][tc] && v-M[tr][tc]<D)
			{
				if(vis[tr][tc]!=mask)
					dfs(tr,tc,v,reached,mask);
			}
			else if( v<M[tr][tc] )
				reached=true;
	}
}

int dfs2(int br,int bc,int v)
{
	vis[br][bc]=1;
	int res=0;
	int r,c,d;
	if(M[br][bc]==v)
	{
	res++;
	V[br][bc]=1;
	}

	for(d=0;d<4;d++)
	{
		r=br+dr[d];
		c=bc+dc[d];
		if(check(r,c))
			if(v>=M[r][c] && v-M[r][c]<D)
				if(!vis[r][c])
					res+=dfs2(r,c,v);
	}
	return res;
}

int solve()
{
	int r,c,res=0;
	for(r=1;r<=R;r++)
		for(c=1;c<=C;c++)
		{
			V[r][c]=true;
			vis[r][c]=-1;
		}
		for(r=1;r<=R;r++)
			for(c=1;c<=C;c++)
				if(V[r][c])
				{
					bool reached=false;
					dfs(r,c,M[r][c],reached,r*C+c);
					if(!reached)
						V[r][c]=true;

					//	print();

				}

				for(r=1;r<=R;r++)
					for(c=1;c<=C;c++)
						vis[r][c]=0;

				for(r=1;r<=R;r++)
					for(c=1;c<=C;c++)
						if(V[r][c]&&!vis[r][c])
						{
							res+=dfs2(r,c,M[r][c]);;
						}


				//		print();
						//printf("\n");

						return res;

}

int main()
{
	//freopen("c:/a.txt","r",stdin);
	int r,c;
	scanf("%d",&cas);
	while(cas--)
	{
		scanf("%d%d%d",&R,&C,&D);
		for(r=1;r<=R;r++)
			for(c=1;c<=C;c++)
				scanf("%d",&M[r][c]);
		printf("%d\n",solve());

		//	printf("\n");
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator