http://merlinhool.github.io/2015/01/19/Facebook-Hacker-Cup-2015/
https://www.facebook.com/notes/1047761065239794/
http://joelantonio.me/post/2015/03/29/hacker-cup-round1-solution/
https://www.facebook.com/notes/1047761065239794/
给一棵n个节点的树,表示上司和员工的关系。每个人买一个礼物,价格1-n,要求每个人不能和上司买礼物的价格一样,求最小的总花费。
n <= 2*10^5
Analysis:
首先想了很多贪心策略无果….
O(nlogn)
结论:最优情况下,每个点的点权上限是logn。
证明:设 f(x)表示树中最大点权为x的情况下,树的最小节点数。
换根,以权为x的点为树根,则它有权为1,2,3…x-1的儿子,
故 f(x) >= sum(f(i)) + 1 >= 2^x
得证。
那么很容易做到O(nlogn)的dp吧。
O(n)的dp
注意到,要推出上面的结论,其实基于一个很显然的结论。
设deg(x)表示x的儿子节点的个数,那么一定有best(x) <= deg(x) + 2。
利用这个结论,用和上面差不多的方法dp,只是每次枚举点权的上限不是logn而是deg(x)。
那么,时间复杂度是sum deg(i)。所以是线性的。
http://joelantonio.me/post/2015/03/29/hacker-cup-round1-solution/
This is a kind Graph coloring problem. The employees are the nodes, so we build a vector with adjacency list to save the relation. We use dynamic programming technique to dertemine the sum of all the colors DP[MAXN][MAXK] , what it is MAXK? It is the maximum numbers of colors for each node, so we’ll assume that max color is 32, in otherwise, we will not able to compute it.
For each node we go through all its parents, and after we go throught [1, 32> possible chromatic number, actually we do something like Dijkstra’s algorithm. We have a variable tmp=∞ , so tmp=min(tmp,solving(next,j)) . After that just we add up DP[a][b]+=tmp
The complexity of the problem is (n) , thanks to the DP.
5 vector<int> adj[MAXN];
6 int DP[MAXN][MAXK], J=0;
7
8 int solving(int a, int b){
9 if(DP[a][b] == -1){
10 DP[a][b] = 0;
11 for(int i = 0; i < (int)adj[a].size(); i++){
12 int next = DP[a][i];
13 int tmp = INF;
14 for(int j = 1; j < MAXK; j++){
15 if(b == j) continue;
16 if(tmp > j + solving(next, j)) J = max(J, j);
17 tmp = min(tmp, j + solving(next, j));
18 }
19 DP[a][b] += tmp;
20 }
21 }
22 return DP[a][b];
23 }
24
25 int main(){
26 int t, n, tmp;
27 cin >> t;
28 for(int i = 1; i <= t; i++){
29 cin >> n;
30 for(int e = 0; e <= n; e++) adj[e].clear();
31 for(int j = 1; j <= n; j++){
32 cin >> tmp;
33 adj[tmp].push_back(j);
34 }
35 memset(DP, -1, sizeof(DP));
36 cout << "Case #" << i << ": " << solving(0, 0) << "\n";
37 }
38 return 0;
39 }
https://www.facebook.com/notes/1047761065239794/