Topic:
Xiao Ming accompanied Xiao Red to see the diamonds, they from a bunch of diamonds randomly extracted two and compare their weight. The weight of these diamonds varies. After they had been comparing for some time, they had a fancy for two diamonds G1 and G2. Now, please judge which of the two diamonds is heavier according to the information you have previously compared.
Given the number of two diamonds g1,g2, the number starts at 1, given the relationship array vector, where the elements are some binary groups, the first element is the number of the heavier diamond in a comparison, and the second element is the number of the lighter diamond. The last number of comparisons before given N. Please return the relationship between the two diamonds, if G1 more return 1,g2 more return-1, can not be judged to return 0. The input data is guaranteed to be legal and there will be no contradiction.
Test Examples:2,3,[[1,2],[2,4],[1,3],[4,3]],4returns: 1
1#include <iostream>2#include <vector>3#include <string>4#include <queue>5#include <unordered_map>6#include <algorithm>7 using namespacestd;8 9 /*Ten 1>2 One 2>4 A 1>3 - 4>3 - to determine the relationship between 2 and 3 the If you can traverse to 3 starting from 2, then 2>3, and vice versa 2<3 - breadth-first traversal of similar graphs - 1 Create a hash table that takes the left element as key and the right element as value (vector<int> structure) - 2 begins the breadth-first traversal in G1, until it traverses to G2, then g1>g2; otherwise begins the breadth-first traversal with the G2, until the G1 is traversed, g1<g2; otherwise the condition is not enough to judge + 2.1 The vertices connected to the G1 (that is, the value corresponding to G1 as the key) into the queue sequentially - 2.2 with a hash table tag traversal case, key is vertex, value (bool type) tag is traversed + */ A at classCMP { - BOOLCompareintG1,intG2, unordered_map<int, vector<int>>graph) - { -queue<int>que; - Que.push (G1); -unordered_map<int,int>Flag; in inttemp; - while(!que.empty ()) to { +temp =Que.front (); -Flag[temp] =1; the Que.pop (); * if(temp = =G2) $ return true;Panax Notoginseng Else - { the for(inti =0; i < graph[temp].size (); i++) + { A if(!flag[graph[temp][i]])//if Graph[temp][i] has not been traversed the Que.push (Graph[temp][i]); + } - } $ } $ return false; - } - Public: the intcmpintG1,intG2, vector<vector<int> > Records,intN) { - //Write code hereWuyiunordered_map<int, vector<int>>graph; the for(inti =0; I < n;i++) -graph[records[i][0]].push_back (records[i][1]); Wu if(Compare (G1, G2, graph)) - return 1; About Else $ { - if(Compare (G2, G1, graph)) - return-1; - Else A return 0; + } the } - }; $ the /* the Test Examples: the 2, 3, [[1, 2], [2, 4], [1, 3], [4, 3]], 4 the returns: 1 - */ in intMain () the { thevector<vector<int> > v{{1,2},{2,4},{1,3},{4,3} }; About CMP solution; theCOUT<<SOLUTION.CMP (2,3V4); the return 0; the}
Compare weight NetEase 2016 Internship Development Engineer programming problem