Rank

there are N ACMers in HDU team.
ZJPCPC Sunny Cup 2007 is coming, and lcy want to select some excellent ACMers to attend the contest. There have been M matches since the last few days(No two ACMers will meet each other at two matches, means between two ACMers there will be at most one match). lcy also asks"Who is the winner between A and B?" But sometimes you can't answer lcy's query, for example, there are 3 people, named A, B, C.and 1 match was held between A and B, in the match A is the winner, then if lcy asks "Who is the winner between A and B", of course you can answer "A", but if lcy ask "Who is the winner between A and C", you can't tell him the answer.
As lcy's assistant, you want to know how many queries at most you can't tell lcy(ask A B, and ask B A is the same; and lcy won't ask the same question twice).

Input

The input contains multiple test cases.
The first line has one integer,represent the number of test cases.
Each case first contains two integers N and M(N , M <= 500), N is the number of ACMers in HDU team, and M is the number of matchs have been held.The following M lines, each line means a match and it contains two integers A and B, means A wins the match between A and B.And we define that if A wins B, and B wins C, then A wins C.

Output

For each test case, output a integer which represent the max possible number of queries that you can't tell lcy.

Sample Input

3
3 3
1 2
1 3
2 3
3 2
1 2
2 3
4 2
1 2
3 4

Sample Output

0
0
4

Hint

in the case3, if lcy ask (1 3 or 3 1) (1 4 or 4 1) (2 3 or 3 2) (2 4 or 4 2), then you can't tell him who is the winner.
   
   
   
   
思路:搜索题。定义一个二维数组,初始化0,但是一个对角线要赋值1,
能分出胜负的赋值1,然后计算下1的个数num,最后num要记得减去n,
以为本身对本身不算,即:num-=n;总的可能个数为sum=1+2+...+n;
所以最后为sum-num.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int e[505][505];
int n,m;
void dfs(int p,int q){
	int i,j;
	for(i=1;i<=n;i++){
	    if(e[i][p]==1){    //说明i会赢 
	    	e[i][q]=1;   //所以i和q之间i会赢 
	    	for(j=1;j<=n;j++){
	    		if(e[q][j]==1){   
	    			e[i][j]=1;  //同理 
	    		}
	    	}
	    }
	}
}
int main(){
	int t;
	cin >>t;
	while(t--){
		memset(e,0,sizeof(e));
		cin >>n>>m;
		for(int i=1;i<=n;i++)
		 e[i][i]=1;
		 for(int i=1;i<=m;i++){
		 	int x,y;
		 	scanf("%d%d",&x,&y);
		 	e[x][y]=1;
		 	dfs(x,y);
		 }
		 int sum=0,num=0;
		 for(int i=1;i<=n;i++){
		 	for(int j=1;j<=n;j++){
		 		if(e[i][j]==1){
		 			num++;
		 		}
		 	}
		 }
		 num-=n;
		 for(int i=1;i<=n-1;i++)
		 sum+=i;     //总共有sum条通路 
		 printf("%d\n",sum-num);
	}
	return 0;
}


你可能感兴趣的:(DFS)