1.题目描述:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 11280 | Accepted: 6262 |
Description
N (1 ≤ N ≤ 100) cows, conveniently numbered 1..N, are participating in a programming contest. As we all know, some cows code better than others. Each cow has a certain constant skill rating that is unique among the competitors.
The contest is conducted in several head-to-head rounds, each between two cows. If cow A has a greater skill level than cow B (1 ≤ A ≤ N; 1 ≤ B ≤ N; A ≠ B), then cow A will always beat cow B.
Farmer John is trying to rank the cows by skill level. Given a list the results of M (1 ≤ M ≤ 4,500) two-cow rounds, determine the number of cows whose ranks can be precisely determined from the results. It is guaranteed that the results of the rounds will not be contradictory.
Input
* Line 1: Two space-separated integers: N and M
* Lines 2..M+1: Each line contains two space-separated integers that describe the competitors and results (the first integer, A, is the winner) of a single round of competition: A and B
Output
* Line 1: A single integer representing the number of cows whose ranks can be determined
Sample Input
5 5 4 3 4 2 3 2 1 2 2 5
Sample Output
2
Source
2.题意概述:
有n只奶牛,有n个连续的实力,如果u的实力大于v的实力,就能打赢它,
然后给定m种关系,求最后能确定其排名的奶牛个数。
3.解题思路:
离散的知识——传递闭包:有向图的传递闭包就是指有向图所有传递关系中的最小关系
如果一头牛被x头牛打败,并且可以打败y头牛,如果x+y=n-1,则我们容易知道这头牛的排名就被确定了,所以我们只要将任一头牛,可以打败其他的牛的个数x, 和能打败该牛的牛的个数y求出来,在遍历所有牛判断一下是否满足x+y=n-1,就知道这个牛的排名是否能确定了(而传递闭包,正好将所有能得出关系都求出来了), 再将满足这个条件的牛数目加起来就是所求解。 x可以看成是入度, y是出度。
在floyd-warshall求每对顶点间的最短路径算法中,可以通过O(v^3)的方法求出图的传递闭包。可以位每条边赋以权值1,然后运行Floyd-Wareshall。如果从 i 到 j 存在一条路径,则mp(i,j)
一种改进的算法是:由于我们需要的只是判断是否从i到j存在一条通路,所以在Floyd-Wareshall中的动态规划比较中,我们可以把min和+操作改为逻辑or( || )和逻辑(&&)。也就是将 mp[i][j] = min(mp[i][j], mp[i][k]+mp[k][j]); 改成 if(mp[i][j] == 1 || (mp[i][k] == 1 && mp[k][j] == 1)) mp[i][j] = 1;
设 mp(i,j) = 1表示从 i 到 j 存在一条通路 p,且 p 的所有中间节点都在0,1,2,...,k中, 否则mp(i,j)=0。我们把边(i,j)加入到E*中当且仅当mp(i,j)=1。
4.AC代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include