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.
InputFor 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.
<h4< dd="">OutputFor each case, we need exactly one integer as output, which is the minimal width of the shelf.
<h4< dd="">Sample Input3 1 1 7 1 1 2 2 3 3<h4< dd="">Sample Output
2 3<h4< dd="">Hint
Case 1 is the example.
Case 2:
This problem contains massive input and output, please use efficient IO methods.
#include <bits/stdc++.h>
using namespace std;
vector<int>p[10005];
int dp[10005]; //记录各节点宽度
void dfs(int n)
{
int s=p[n].size();
if(s==0) dp[n]=1; //无父节点,其宽度为自身,1
else if(s==1)
{
dfs(p[n][0]); //得到父节点宽度
dp[n]=dp[p[n][0]]; //相等
}
else
{
int u=p[n][0],v=p[n][1]; //上连两个节点
dfs(u);
dfs(v); //各自最小宽度
if(dp[u]==dp[v]) //宽相等时相连总宽度+1
dp[n]=dp[u]+1;
else dp[n]=max(dp[u],dp[v]);
}
}
int main()
{
int n;
while(cin>>n)
{
memset(dp,0,sizeof(dp));
for(int i=1; i<=n; i++)
p[i].clear();
for(int i=1; i<n; i++)
{
int t;
cin>>t;
p[t].push_back(i+1);
}
dfs(1);
cout<<dp[1]<<endl; //到达终点时宽度
}
}