描述
給出兩個list x,y,代表x[i]與y[i]之間有一條邊,整個邊集構成一棵樹,1爲根,現在有個list a,b,表示詢問節點a[i]與b[i]是什麼關係,如果a[i]與b[i]是兄弟,即有同一個父節點,輸出1,如果a[i]與b[i]是父子關係,輸出2,否則輸出0。
節點數不大於100000。
所以的數均爲不大於100000的正整數
樣例
給出 x = [1,1], y = [2,3], a =[1,2], b = [2,3], 返回[2,1]。
解釋:
1與2是父子關係,2與3是兄弟關係,它們的共同父節點爲1。
給出 x = [1,1,2], y = [2,3,4], a = [1,2,1], b = [2,3,4], 返回[2,1,0]。
解釋:
1與2是父子關係,2與3是兄弟關係,它們的共同父節點爲1,1與4不是兄弟關係也不是父子關係。
思路
見代碼
僅AC 50%
#ifndef C1413_H
#define C1413_H
#include<iostream>
#include<vector>
#include<map>
#include<set>
using namespace std;
class Solution {
public:
/**
* @param x: The x
* @param y: The y
* @param a: The a
* @param b: The b
* @return: The Answer
*/
vector<int> tree(vector<int> &x, vector<int> &y, vector<int> &a, vector<int> &b) {
// Write your code here
vector<int> res;
if (x.empty() || y.empty() || a.empty() || b.empty())
return res;
vector<vector<int>> vec(100001, vector<int>());//存放結點的對應關係
map<int, int> dic;//存放結點及其父節點
for (int i = 0; i < x.size(); ++i)
{
vec[x[i]].push_back(y[i]);
vec[y[i]].push_back(x[i]);
}
//構建vec
dfs(1, 0, dic, vec);
for (int i = 0; i < a.size(); ++i)
res.push_back(getRelationship(a[i], b[i], dic));
return res;
}
void dfs(int node, int root, map<int, int> &dic, vector<vector<int>> &vec)
{
dic[node] = root;
for (auto c : vec[node])
{
if (c != root)
{
dfs(c, node, dic, vec);
}
}
}
//返回兩個節點的關係
int getRelationship(int node1, int node2, map<int, int> dic)
{
if (dic[node1] == node2 || dic[node2] == node1)
return 2;
else if (dic[node1] == dic[node2])
return 1;
return 0;
}
};
#endif