Coding练习题-钻石重量比较
小明陪小红去看钻石,他们从一堆钻石中随机抽取两颗并比较她们的重量。这些钻石的重量各不相同。在他们们比较了一段时间后,它们看中了两颗钻石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) {// first construct directed graph, at most 2n diamonds // node index start from 1 vector<vector<int> > dgraph(2*n+1); // num of diamondsint cnt=0;for(int i=0; i0]);dgraph[records[i][0]].push_back(records[i][1]);}//bfs search for g1/g2vector<int> next;vector<bool> visted(cnt+1,false);int candidate[2]{g1,g2};int ret[2]{1,-1};for(int i=0; i<2; ++i){next.clear();visted.assign(cnt+1,false);next.push_back(candidate[i]);while(!next.empty()){int diamond=next.back();next.pop_back();// check if we have visted this diamondif(visted[diamond]==true)continue;else visted[diamond]=true;// if we find another diamondif( candidate[1-i] == diamond) return ret[i]; if(!dgraph[diamond].empty()){for(int d:dgraph[diamond]){if(!visted[d])next.push_back(d); }}}}return 0;}
};
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
