Program design thinking and practice Week7 job A-TT magic cat

Topic Link: A-TT magic cat

Topic Description:
As we all know, TT has a magic cat.
On this day, TT is dedicated to playing "cat and mouse" game, but the game has not started, the wise magic cat will tell the final results TT race. TT very surprised, not surprised at his little cat actually talking more surprised at this cute little point why not have such magic?
Magic cat told TT, it has in fact the outcome of a game table, there are individuals N and M relationship between the outcome above, each relationship between the outcome of AB, said A can beat B, and the outcome of the relationship is transitive. I.e. A than B, B than C, then A can be better than C.
TT did not believe what he little cat can predict the game, so he wondered how many of the players know in advance the outcome can not, can you help him?

Input:
The first line gives the number of data groups.
Each data of the first line gives the N and M (N, M <= 500 ).
Next M rows, each row gives AB, it can be better than B. A represents

Output:
For each set of data, it is determined how much the outcome of the game can not be known in advance. Note (a, b) and (b, a) is equivalent, i.e., each tuple is calculated only once.

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

Ideas:
This title use Floyd algorithm to indicate the outcome of transitive relations. First saved with the N-dimensional matrix outcome of the relationship between each person, is initialized to 0, showing the relationship between the outcome is unknown, and then performing the Floyd algorithm processing to be performed triple loop, to ensure the transmission of the outcome of the relationship. While pruning operation, the group has only deal with the outcome of the relationship. On output, since the outcome of the relationship between the two is determined, and thus considering only half of the matrix (not including the diagonal itself).

Summary:
This question is basically applied the algorithm, keeping in mind pruning, reducing complexity.

Code:

#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
int path[510][510];
int main(){
	//freopen("in.txt","r",stdin);
	int T,N,M,A,B,cnt;
	cin>>T;
	while(T--){
		cnt=0;
		memset(path,0,sizeof(path)); 
		cin>>N>>M;
		for(int i=0;i<M;i++){
			cin>>A>>B;
			path[A][B]=1;
		}
		for(int i=1;i<=N;i++)
		  	for(int j=1;j<=N;j++)
		  		if(path[j][i]==1)
		    		for(int k=1;k<=N;k++)
		    			if(path[i][k]==1)
		    				path[j][k]=1;
		for(int i=1;i<=N;i++)
			for(int j=1;j<=N;j++)
				if(i!=j&&path[i][j]==0&&path[j][i]==0)
					cnt++;
		cout<<cnt/2<<endl;
	}
}
Published 25 original articles · won praise 0 · Views 587

Guess you like

Origin blog.csdn.net/qq_43666020/article/details/105312584