Cow Contest#10151

Cow Contest (Талдау)

Let us define a Boolean matrix . For each pair of cows and , set g[a][b] = true if cow defeats cow . In other words, we draw a directed edge from to . Since the results of the rounds are consistent, the resulting graph is acyclic.

The rank of cow can be determined if, for every other cow , we know which of them is stronger: either cow can defeat cow (possibly through several intermediate cows), or cow can defeat cow . In other words, in the transitive closure of the graph, for every pair and , at least one of the following conditions must hold: g[i][j] = true or g[j][i] = true.

Both g[i][j] and g[j][i] cannot be at the same time, because that would imply a contradiction in the competition results.

Example

In the example above, the ranks can be determined unambiguously only for cows and .

Cow Cow but loses to all the other cows. Cow loses to all the other cows.

For cow it is unknown whether she can beat cows and . Similarly, for cows and it is unknown whether they can beat cow . Therefore, the exact ranks of these cows cannot be determined.

Algorithm implementation

Define a boolean matrix .

bool g[101][101];

Read the input data.

scanf("%d %d", &n, &m);

Assume that every cow beats itself.

for (i = 1; i <= n; i++) g[i][i] = 1;

Read the input data and construct the directed graph. If cow beats cow , add a directed edge from to .

for (i = 0; i < m; i++)
{
  scanf("%d %d", &a, &b);
  g[a][b] = 1;
}

Compute the transitive closure of the graph. If there is a path from vertex to vertex , set g[i][j] = true.

for (k = 1; k <= n; k++)
for (i = 1; i <= n; i++)
for (j = 1; j <= n; j++)
  if (g[i][k] && g[k][j]) g[i][j] = true;

Use the variable to keep track of the number of cows whose ranks can be determined unambiguously.

res = 0;

In the loop, check each cow one by one and determine whether its rank can be determined unambiguously.

for (i = 1; i <= n; i++)
{

Check whether the rank of cow can be determined. To do this, we iterate over all cows . If, for some cow, both conditions hold: g[i][j] = false and g[j][i] = false, then it is impossible to determine which of the two cows is stronger. Therefore, the exact rank of cow cannot be determined.

  bool good = true;
  for (j = 1; j <= n; j++)
    if (g[i][j] == false && g[j][i] == false)
    {
      good = false;
     break;
    }

If, after checking all cows, the value of remains , then the position of cow relative to every other cow is known. Therefore, its rank can be determined unambiguously.

  if (good) res++;
}

Print the answer.

printf("%d\n", res);