Week7 A-The Magic Cat of TT

Problem 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?
The
first line of input 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 determined how much the outcome of the game can not be known in advance. Note that (a, b) is equivalent to (b, a), that is, each binary is calculated only once.

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

Ideas

Because the win-loss relationship is transitive, the idea of ​​the transitive closure is used here. The Floyd algorithm can be used to find the win-loss relationship of any two points (pass-through closure), and the answer can be obtained, a [i] j] = 1 means that i is stronger than j, a [i] [j] = 0 means that the relationship between i and j is unknown, a [i] [j] = 0 and a [j] [i] = 0 means The relationship between i and j cannot be pre-judged. Using the transitivity of win and loss, a [i] [k] = 0 eliminates the need to perform the next level of search, saving a for loop and finally calculating a [ i] [j] = 0 and a [j] [i] = 0 The number of points, please pay attention to traversing the upper right or upper left of the matrix to avoid double calculation

Code

#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std; 
int n,m,c,t1,t2,cnt; 
bool a[501][501]; 
int main() {
    
    scanf("%d", &c);  
    while (c--)
    {
        cnt=0;
        memset(a,0,sizeof(a)); 
        scanf("%d%d", &n,&m);  
        for(int i=0;i<m;i++)
        {
            scanf("%d%d", &t1,&t2);
            a[t1][t2]=1;   
        }
        for(int k=1;k<=n;k++)
        for(int i=1;i<=n;i++)
        if(a[i][k])
        {
            for(int j=1;j<=n;j++)
            {
                if(a[i][j])continue;
                a[i][j]=a[i][k]&&a[k][j];
            }
        }

        for(int i=1;i<=n;i++)
        for(int j=i+1;j<=n;j++)
        {
           if(!a[i][j]&&!a[j][i])cnt++;
        }
        printf("%d\n",cnt);
    }
      
   // system("pause");
    return 0;
}
Published 20 original articles · praised 3 · visits 449

Guess you like

Origin blog.csdn.net/qq_44893580/article/details/105315627
TT