读完题后,感觉是个有向图,我的理解是对于一个点(这里即所谓person),取所有能走到这个点的点里对应的quiet最小的点。找能到达点x的点集中最小quiet的这个过程可定义为Func(x),这样问题就简化为了对点x,找与x有直接关联的(即存在于richer数组中)的点集ys中的min(Func(y)),可用递归实现。
public class Solution {
int[] q ;
List<List<int>> list = new List<List<int>>();
int[] a;
public int[] LoudAndRich(int[][] richer, int[] quiet) {
q = quiet;
for(int i = 0; i < quiet.Length; i++)
{
list.Add(new List<int>());
list[i].Add(i);
}
for(int i = 0; i < richer.Length; i++){
list[richer[i][1]].Add(richer[i][0]);
}
a = new int[quiet.Length];
for(int i = 0; i < q.Length; i++){
a[i] = -1;
}
for(int i = 0; i < q.Length; i++){
a[i] = func(list[i],i);
}
return a;
}
int func(List<int> ll,int index)
{
int min = int.MaxValue;
int res = -1;
if(ll.Count() == 1)
{
return ll[0];
}
for(int i = 0; i < ll.Count(); i++)
{
int j = ll[i];
int temp = -1;
if(j == index)
temp = index;
else
{
if(a[j] != -1)
temp = a[j];
else
temp = func(list[j],j);
}
if(q[temp] < min)
{
min = q[temp];
res = temp;
}
}
return res;
}
}