本帖最後由 許浩浩 於 2025-3-22 07:16 編輯
1. APCS 實作題:
10503 - 4- #include<bits/stdc++.h>
- using namespace std;
- int n,root;
- int res,finalMaxChildDis;
- struct Node
- {
- int parent=-1,h=0;
- int maxChildDis=-1,max=-1,sec=-1;
- vector<int> child;
- };
- int main()
- {
- cin.tie(0);
- cin.sync_with_stdio(0);
- while(cin>>n)
- {
- finalMaxChildDis=-1;
- Node node[n];
- for(int i=0;i<n-1;i++)
- {
- int p,c;
- cin>>p>>c;
- node[c].parent=p;
- node[p].child.push_back(c);
- }
- for(int i=0;i<n;i++)
- {
- if(node[i].parent==1)
- root=i;
- if(node[i].child.size()==0)
- {
- int h=0;
- int parent=node[i].parent;
- while(parent!=-1)
- {
- h++;
- if(h>node[parent].h)
- node[parent].h=h;
- else
- break;
- parent=node[parent].parent;
- }
- }
- }
- for(int i=0;i<n;i++)
- {
- if(node[i].child.size()>=2)
- {
- for(int j=0;j<node[i].child.size();j++)
- {
- int childH=node[node[i].child[j]].h;
- if(childH>node[i].max)
- {
- node[i].sec=node[i].max;
- node[i].max=childH;
- }
- else if(childH>node[i].sec)
- node[i].sec=childH;
- }
- node[i].maxChildDis=node[i].max+node[i].sec+2;
- if(node[i].maxChildDis>finalMaxChildDis)
- finalMaxChildDis=node[i].maxChildDis;
- }
- }
- if(node[root].h>finalMaxChildDis)
- res=node[root].h;
- else
- res=finalMaxChildDis;
- cout<<res<<endl;
- }
- return 0;
- }
複製代碼 2. APCS 觀念題:10510 - 12、13 |