ZOJ 3805 Machine(简单dp)
In a typical assembly line, machines are connected one by one. The first machine‘s output product will be the second machine‘s raw material. To simplify the problem, we put all machines into a two-dimension shelf. Every machine occupied exactly one grid and has two input ports and only one output port. One input port can get material from only one machine.
Pipes will be used to connect between these machines. There are two kinds of pipes : ‘I‘ kind and ‘L‘ kind. We should notice that the ‘I‘ kind pipe can be linked one by one. Each pipe will also occupied one grid.
In Bob‘s factory, each machine will get raw materials from zero, one or two other machines. Some machines don‘t need any input materials, but any machine must have an output. Machines are coded by numbers from 1 to n. The output of the machines with greater code can be the input of the machines with less code. The machine NO.1‘s output product will be the final product, and will not be any other machine‘s input. Bob‘s factory has a shelf with infinite height, but finite width. He will give you the dependency relationship of these machines, and want you to arrange these machines and pipes so that he can minimize the width of the shelf.
Here‘s an example for you to help understand :
Products will falling from higher machine to lower machine through the pipes. Here, machine 1 gets materials from machine 2 and machine 3. The whole width of this system is 2.
Input
For each case, the first line will be an integer n indicates the number of the machines (2≤ n≤ 10000). The following line will include n-1 numbers. The i-th number ai means that the output of machine i+1 will be the input of machine ai (ai≤ i). The same code will be appeared at most twice. Notice machine 1‘s output will be the final output, and won‘t be any machine‘s input.
Output
For each case, we need exactly one integer as output, which is the minimal width of the shelf.
Sample Input
3 1 1 7 1 1 2 2 3 3
Sample Output
2 3
Hint
Case 1 is the example.
Case 2:
题意:有 n 个不同的机器,他们之间的生产关系构成一棵二叉树,要求使用管道把它们连接起来完成这个生产线,并使得整体的宽度最小 ,管道只有L型和直线型两种(具体形状见题目),不能旋转管道。每台机器最多有2个输入口和1个输出口。
#include <cstdio> #include <cstring> #include <algorithm> #include <vector> using namespace std; const int N = 1e4 + 5; vector <int> v[N]; int dp[N]; void dfs(int u) { int sz = v[u].size(); if(sz == 0) dp[u] = 1; else if(sz == 1) { dfs(v[u][0]); dp[u] = dp[v[u][0]]; } else { int s1 = v[u][0], s2 = v[u][1]; dfs(s1); dfs(s2); if(dp[s1] == dp[s2]) dp[u] = dp[s1] + 1; else dp[u] = max(dp[s1], dp[s2]); } } int main() { int n, a; while(~scanf("%d", &n)) { for(int i = 1; i <= n; i++) v[i].clear(); for(int i = 2; i <= n; i++) { scanf("%d", &a); v[a].push_back(i); } dfs(1); printf("%d\n", dp[1]); } return 0; }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。