首页 > ACM题库 > HDU-杭电 > HDU 2868-Neighbor Friend-最短路径-[解题报告]HOJ
2014
02-17

HDU 2868-Neighbor Friend-最短路径-[解题报告]HOJ

Neighbor Friend

问题描述 :

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 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.

输出:

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.

样例输入:

3 1
1 2
3 2
1 2
2 3

样例输出:

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.

小规模用floyd

#include <list>
#include <map>
#include <set>
#include <queue>
#include <string>
#include <deque>
#include <stack>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <limits.h>
#include <time.h>
#include <string.h>
using namespace std;

#define LL long long
#define PI acos(-1.0)
#define Max INT_MAX
#define Min INT_MIN
#define eps 1e-8
#define FRE freopen("a.txt","r",stdin)
#define N 201
bool g[N][N];
bool gg[N][N];
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        int i,j,k;
        memset(g,false,sizeof(g));
        memset(gg,false,sizeof(gg));
        while(m--){
            int a,b;
            scanf("%d%d",&a,&b);
            g[a][b]=true;
        }
        int res=0;
        for(i=1;i<=n;i++)
        for(j=1;j<=n;j++)
        for(k=1;k<=n;k++)
        if(g[j][i] && g[i][k]){
            g[j][k]=gg[j][k]=true;     // 注意:1 2 2 3 3 4 4 5这组数据,要连上1-3,1-4,1-5。。。。
            //cout<<j<<" "<<k<<endl;
        }
        for(i=1;i<=n;i++)
        for(j=i+1;j<=n;j++)
        if(gg[i][j] || gg[j][i])
        res++;

        printf("%d\n",n*(n-1)/2-res);
    }
    return 0;
}

解题参考:http://blog.csdn.net/leolin_/article/details/6720231


  1. 您没有考虑 树的根节点是负数的情况, 若树的根节点是个很大的负数,那么就要考虑过不过另外一边子树了