Suppose we sort N persons in a line according to their heights,we are curious about the Neighbor Friend.
A pair of Neighbor Friend is two person next to each other in the line,ignoring the order(ie (x,y) and (y,x)is the same).
Now you are given M pieces of infomation,each with two integer a and b,discribing that person a is shorter than person b.
Can you find how many different pairs of Neighbor Friend that could occur in some of the sorted line?
Input
Input contains multiple cases.
Each test case starts with two integer N(2<=N<=200) ,M(0<=M<1000) ,indicating that there are N persons and M pieces of information.Follow by M lines,each line contains two integers a and b,represents that person a is shorter than person b.
Output
For each test case, output the different pairs of Neighbor Friend that could occur in some of the sorted line.
Sample Input
3 1
1 2
3 2
1 2
2 3
Sample Output
3
2
Hint
Hint
In sample 1,we know that person 1 is shorter than person 2, there may be three kind of sorted results: 3 1 2,1 3 2,1 2 3.(1,3),(1,2) and (2,3) could be found among them.
In sample 2,we know that person 1 is shorter than person 2,and person 2 is shorter than person 3,so there is only one kind of sorted results:1 2 3.We can’t find (1,3),so
the answer is 2.
题意:大概的意思就是 给你几个已经定好的身高关系 每一行 a<b
然后把所有符合这些身高关系的排序方式列出来 ,找出所有的相邻无序对
看一下样例会好理解很多
题解 假如 三个人 a<b<c 那么ac无论怎么排序都是不可能在一起的 抽象到图论上就是距离等于2
那么除了这种大于2的其他的都有可能在一起
用floyd找一下距离小于2的就行了
#include <bits/stdc++.h>
#define maxn 1000+5
#define INF 0x3f3f3f3f
using namespace std;
int g[maxn][maxn];
int main(){
int n,m;
while(scanf("%d%d",&n,&m)!=EOF){
memset(g,0,sizeof(g));
for(int i=0;i<m;i++){
int a,b;
scanf("%d%d",&a,&b);
g[a][b]=1;
}
for(int k=1;k<=n;k++){
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(g[i][k]&&g[k][j])
g[i][j]=2;
}
}
}
int ans=0;
for(int i=1;i<=n;i++){
for(int j=i+1;j<=n;j++){
if(g[i][j]<2&&g[j][i]<2)
ans++;
}
}
printf("%d\n",ans);
}
}