小明陪小紅去看鑽石,他們從一堆鑽石中隨機抽取兩顆並比較她們的重量。這些鑽石的重量各不相同。在他們們比較了一段時間後,它們看中了兩顆鑽石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 diamonds
int cnt=0;
for(int i=0; i<n; ++i){
cnt = max(cnt, records[i][0]);
dgraph[records[i][0]].push_back(records[i][1]);
}
//bfs search for g1/g2
vector<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 diamond
if(visted[diamond]==true)
continue;
else visted[diamond]=true;
// if we find another diamond
if( 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;
}
};