The Magic Cat of Week7 A TT

Title description

As we all know, TT has a magic cat.

On this day, TT was devoted to playing the "Cat and Mouse" game, but before the game started, the smart magic cat told the final result of the TT game. TT is very surprised. Not only is his kitten actually talking, but also why is this cute little girl so magical?

Magic Cat tells TT that it actually has a game win-loss table with N individuals and M win-loss relationships. Each win-loss relationship is AB, indicating that A can win B, and the win-loss relationship is transitive. That is, A beats B, and B beats C, so A can beat C.

TT does n’t believe that his kitten can predict any game, so he wants to know how many players ’outcomes cannot be known in advance. Can you help him?

Input

The first line gives the number of data groups.

The first line of each set of data gives N and M (N, M <= 500).

In the next M lines, each line is given AB, indicating that A can beat B.

Output

For each set of data, it is impossible to know in advance how many games are won or lost. Note that (a, b) is equivalent to (b, a), that is, each binary 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

Imagine the player as a point in the figure, and convert a victory over b into a directed edge with a length of 1 between the two points of ab, and you can use the Floyd algorithm to solve it. It is mainly to change the update of the directed edge between any two points to dis [i] [j] = max (dis [i] [j], dis [i] [k] & dis [k] [j]), so When the algorithm is finished, all points are considered as the intermediate points to pass the win-loss relationship, that is, all win-loss relationships are obtained. If dis [i] [j] and dis [j] [i] are both zero, it means The outcome is unclear, otherwise, the relationship is clear.

Code

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 505;
int n, m, a1, b1, ans, temp;
int dis[N][N];

void Floyd()
{
	for (int k = 1; k <= n; k++)
		for (int i = 1; i <= n; i++)
			if (dis[i][k] != 0)
			{
				for (int j = 1; j <= n; j++)
					dis[i][j] = max(dis[i][j], dis[i][k] & dis[k][j]);
			}
}

int main()
{
	scanf_s("%d", &temp);
	for (int i = 0; i < temp; i++)
	{
		memset(dis, 0, sizeof(dis));
		scanf_s("%d%d", &n, &m);
		ans = 0;
		for (int j = 0; j < m; j++)
		{
			scanf_s("%d%d", &a1, &b1);
			dis[a1][b1] = 1;
		}
		Floyd();
		for (int k = 1; k <= n; k++)
			for (int l = 1; l <= n; l++)
				if (dis[k][l] == 0 && dis[l][k] == 0&&k!=l)
					ans++;
		ans /= 2;
		printf("%d\n", ans);
	}
    return 0; 
}
Published 32 original articles · praised 0 · visits 675

Guess you like

Origin blog.csdn.net/qq_43814559/article/details/105545036
TT