TT's magic cat

Title:
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, judging how many games win or lose cannot be known in advance. 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

Problem-solving ideas: This problem is mainly to find the transitivity of the path, a-> b, b-> c then a-> c; use the floyd algorithm to find this thing in n ^ 3 time; then you can solve it with a little care .

Code:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int a[500][500];
int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        memset(a,0,sizeof(a));
        int c,d;
        scanf("%d%d",&c,&d);
        while(d--)
        {
            int x,y;
            scanf("%d%d",&x,&y);
            a[x-1][y-1]=1;
        }
        int t=c*(c-1)/2;
        for(int k=0;k<c;k++)
        {
            for(int i=0;i<c;i++)
            {
                if(a[i][k]==0){continue;}//剪枝
                for(int j=0;j<c;j++)
                {
                    if(a[i][j]==1||a[k][j]==1)
                    {
                        a[i][j]=1;
                    }
                }
            }
        }
        int total=0;
        for(int i=0;i<c;i++)
        {
            for(int j=0;j<c;j++)
            {
                if(a[i][j]==1)//对称性
                {
                    a[j][i]=1;
                }
            }
        }
        for(int i=0;i<c;i++)
        {
            for(int j=i+1;j<c;j++)//求总共的可以判断的比赛
            {
                if(a[i][j]==1)
                {
                    total++;
                }
            }
        }
        total=t-total;
        printf("%d\n",total);
    }
}
PGZ
Published 34 original articles · praised 0 · visits 868

Guess you like

Origin blog.csdn.net/qq_43653717/article/details/105291409