POJ 3360-Cow Contest(傳遞閉包)

大白QQly成長日記發表於2018-09-11

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 ≤ AN; 1 ≤ BN; AB), 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

題目大意:給出n個點,m條單向邊(A等級高就能打敗B),輸出最終能確定等級的個數。

思路:剛開始看的時候一頭霧水,需要明確找的到底是什麼,是最能與其他點構成連通的中間點,然後想的是跑全圖來鬆弛所有的點,最後找出與所有點相連的點。理論上講這個思路和題意是吻合的,但是,,,沒辦法確定數量啊,因為最終形成的是一個網狀關係圖,無法判斷端點是否為已確定的.......然後就接觸到了傳說中的傳遞閉包。

傳遞閉包的定義:通過矩陣乘法的特性進行傳遞,得到一個完全的可到達的關係圖。(有點表述不清)

簡單描述一下怎麼利用矩陣乘法的。存圖的時候單向邊存1表示有路,用矩陣的每行乘以每列,即與矩陣的轉置相乘,如何理解,轉置後行變成了列,最終矩陣的(x1,y1)就表示原矩陣第x1行與轉置矩陣第y1列相乘的結果,即為點x1連線的情況與點y1連線情況的傳遞,最終得出的矩陣就是傳遞完的圖,但弗洛伊德是借用了這個結論,通過列舉中間點的情況來模擬傳遞的過程,而不是直接用矩陣解。同理,DFS傳遞閉包的實現利用了這個過程,通過不斷的搜尋相關點來模擬這個行列相乘的傳遞過程。

                      

                            想了解一下DFS傳遞閉包:連結太長了,不美觀

只能感嘆,還好我大二了,剛學了矩陣.......(同時感謝昨晚半夜還熱情為我講解的大佬)

補上這個東西后這道題就十分明瞭了,這個傳遞閉包的實現方式可以選擇弗洛伊德或者DFS,前者時間複雜度為(V^3),後者時間複雜度為(VE)。視情況選擇嘍。

程式碼如下:

#include<set>
#include<map>
#include<list>
#include<deque>
#include<cmath>
#include<queue>
#include<stack>
#include<string>
#include<vector>
#include<stdio.h>
#include<sstream>
#include<stdlib.h>
#include<string.h>
//#include<ext/rope>
#include<iostream>
#include<algorithm>
#define pi acos(-1.0)
#define INF 0x3f3f3f3f
#define per(i,a,b) for(int i=a;i<=b;++i)
#define LL long long 
#define swap(a,b) {int t=a;a=b;b=t} 
using namespace std;
//using namespace __gnu_cxx;
int p[105][105];
int main()
{
	int n,m,a,b;
	cin>>n>>m;
	memset(p,0,sizeof(p));
	while(m--)
	{
		cin>>a>>b;
		p[a][b]=1;
	}
    per(k,1,n)
    {
    	per(i,1,n)
    	{
    		per(j,1,n)
    		{
    			if(p[i][k]==1&&p[k][j]==1)//矩陣特性 
    			{
    				p[i][j]=1;
				}
			}
		}
	}
	int k=0,j;
	per(i,1,n)
	{
		for(j=1;j<=n;j++)
		{
			if(i==j) continue;
			if(p[i][j]==0&&p[j][i]==0)
			{
				break;
			}
		}
		if(j>n) k++;
	}
	printf("%d",k);
	return 0;
} 

 

相關文章