[编程题] 比较重量

来源:互联网 发布:下载电子邮箱软件 编辑:程序博客网 时间:2024/04/28 20:14

小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石g1和g2。现在请你根据之前比较的信息判断这两颗钻石的哪颗更重。
给定两颗钻石的编号g1,g2,编号从1开始,同时给定关系数组vector,其中元素为一些二元组,第一个元素为一次比较中较重的钻石的编号,第二个元素为较轻的钻石的编号。最后给定之前的比较次数n。请返回这两颗钻石的关系,若g1更重返回1,g2更重返回-1,无法判断返回0。输入数据保证合法,不会有矛盾情况出现。
测试样例:
2,3,[[1,2],[2,4],[1,3],[4,3]],4
返回: 1

class Cmp {public:    int cmp(int g1, int g2, vector<vector<int> > records, int n) {        map<int,vector<int>> graph;        for(int i=0;i<n;i++)            graph[records[i][0]].push_back(records[i][1]);        if(deepSerach(g1,g2,graph))            return 1;        else if(deepSerach(g2,g1,graph))            return -1;        else            return 0;    }    bool deepSerach(int g1,int g2,map<int,vector<int>>& graph){        queue<int> tmp;        tmp.push(g1);        map<int,int> flag;        while(!tmp.empty()){            int frontValue=tmp.front();            flag[frontValue]=1;            tmp.pop();            if(frontValue==g2)                return true;            for(int i=0;i<graph[frontValue].size();i++) {                if(flag[graph[frontValue][i]]!=1)                    tmp.push(graph[frontValue][i]);            }        }        return false;    }};
0 0