POJ1975 Median Weight Bead floyd传递闭包

时间:2022-03-31 06:44:49

Description

There are N beads which of the same shape and size, but with different weights. N is an odd number and the beads are labeled as 1, 2, ..., N. Your task is to find the bead whose weight is median (the ((N+1)/2)th among all beads). The following comparison has been performed on some pairs of beads: 
A scale is given to compare the weights of beads. We can determine which one is heavier than the other between two beads. As the result, we now know that some beads are heavier than others. We are going to remove some beads which cannot have the medium weight.

For example, the following results show which bead is heavier after M comparisons where M=4 and N=5.

1.	Bead 2 is heavier than Bead 1.

2. Bead 4 is heavier than Bead 3.

3. Bead 5 is heavier than Bead 1.

4. Bead 4 is heavier than Bead 2.

From the above results, though we cannot determine exactly which is the median bead, we know that Bead 1 and Bead 4 can never have the median weight: Beads 2, 4, 5 are heavier than Bead 1, and Beads 1, 2, 3 are lighter than Bead 4. Therefore, we can remove these two beads.

Write a program to count the number of beads which cannot have the median weight.

Input

The first line of the input file contains a single integer t (1 <= t <= 11), the number of test cases, followed by the input data for each test case. The input for each test case will be as follows: 
The first line of input data contains an integer N (1 <= N <= 99) denoting the number of beads, and M denoting the number of pairs of beads compared. In each of the next M lines, two numbers are given where the first bead is heavier than the second bead. 

Output

There should be one line per test case. Print the number of beads which can never have the medium weight.
 
Sample
Sample Input

 2

Sample Output

题意:

  有N个珠子,N为奇数,给出一些信息如a b表示a比b重,通过这些信息可以分析出那些珠子按重量排序后,哪个不可能是中间那个,求可以分析出几个。 如果a比b重,b比c重,则a比c重。

思路:

  和poj3660思路一样,如果确定有(n+1)/2 多个比这个重,或者比这个轻,则表示这个珠子一定不是中间那个。计算出度和入度,如果出度大于(n+1)/2 或者 入度大于 (n+1)/2 ,则表示这个不是中间。

代码:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int map[][];
int n,m;
void floyd()
{
for(int k=; k<=n; k++)
for(int i=; i<=n; i++)
for(int j=; j<=n; j++)
if(map[i][k]==&&map[k][j]==)//传递
map[i][j]=;
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n>>m;
memset(map,,sizeof(map));
for(int i=; i<m; i++)
{
int a,b;
cin>>a>>b;
map[a][b]=;
}
floyd();
int ans=;
for(int i=; i<=n; i++)
{
int d=,x=;
for(int j=; j<=n; j++)
{
if(map[i][j])//计算出度
d++;
else if(map[j][i])//计算入度
x++;
}
if(d>=(n+)/||x>=(n+)/)//出度或者入度其中有一个大于(n+1)/2就能证明不是中间
ans++;
}
cout<<ans<<endl;
}
}