因某些原因未能参加比赛,在赛后重新做了一遍,过的题就不写补题了,写两个没过的;
7-9 这题就是先预处理所有人的辈分,用dfs来处理每个人的辈分,一开始我没在函数里写等于,在函数外面运行完在赋值,但是有一个点会超时,看了大佬的之后,就感觉和并查集find函数的简化有点类似,代码:
超时一个点的
#include<bits/stdc++.h> using namespace std; #define LL long long int p[100005]; int ru[100005]; vector<int>ans; int v; int minn=0; int solve(int n,int m) { if(p[n]==-1)return m; if(ru[n]!=0) { // cout<<n<<" "<<ru[n]<<" "<<m<<endl; return m+ru[n]-1; } return solve(p[n],m+1); } int main() { cin>>v; for(int i=1;i<=v;i++) { cin>>p[i]; if(p[i]==-1)continue; } for(int i=1;i<=v;i++) { int num=solve(i,1); ru[i]=num; // cout<<ru[i]<<endl; if(num>minn) { ans.clear(); ans.push_back(i); minn=num; } else if(num==minn)ans.push_back(i); } cout<<minn<<endl; for(int i=0;i<ans.size();i++) { if(i==0) cout<<ans[i]; else cout<<" "<<ans[i]; } }
正确的:
#include<bits/stdc++.h> using namespace std; #define LL long long int p[100005]; int ru[100005]; vector<int>ans; int v; int minn=0; int solve(int n) { if(ru[n]!=0)return ru[n]; return ru[n]=solve(p[n])+1; } int main() { cin>>v; for(int i=1;i<=v;i++) { cin>>p[i]; if(p[i]==-1)ru[i]=1; } for(int i=1;i<=v;i++) { int num=solve(i); //cout<<ru[i]<<endl; if(ru[i]>minn) { minn=ru[i]; } } for(int i=1;i<=v;i++) { if(ru[i]==minn)ans.push_back(i); } cout<<minn<<endl; for(int i=0;i<ans.size();i++) { if(i==0) cout<<ans[i]; else cout<<" "<<ans[i]; } }
7-12 题,这题是找从某一个点进去最远能到哪里,这题起点没说,是每一个点都能做起点,而且后来被经过的点都不会成为最远的点,所以标记一下,在遇到就跳过,然后遍历每个点,但是还是有一个点会超时,代码:
#include<bits/stdc++.h> using namespace std; #define LL long long vector<int>p[100005]; int ma=0,ans=1; int vis[100005]; void solve(int v,int m) { if(p[v].size()==0) { if(m>ma) { ma=m; ans=v; } return ; } for(int i=0;i<p[v].size();i++) { vis[p[v][i]]=1; solve(p[v][i],m+1); } } int main() { int n; cin>>n; for(int i=1;i<=n;i++) { int t; cin>>t; while(t--) { int b; scanf("%d",&b); p[i].push_back(b); } } for(int i=1;i<=n;i++) { if(vis[i]==0) solve(i,0); } cout<<ans<<endl; }
AC代码:
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<double, double> PII; const int maxn = 100000 + 15; const int INF = 0x7fffffff; const double eps = 1e-9; int n; int ceng[maxn]; vector<int> v[maxn]; set<int> s; void dfs(int now, int x) { if (v[now].empty()) { ceng[now] = x; return; } if (ceng[now] > x) return; ceng[now] = x; for (auto i:v[now]) { dfs(i, x + 1); } } int main() { cin >> n; for (int i = 1; i <= n; i++) { int k; cin >> k; for (int j = 1; j <= k; j++) { int t; cin >> t; s.insert(t); v[i].push_back(t); } } for (int i = 1; i <= n; i++) if (s.find(i) == s.end()) dfs(i, 1); int ansM = 0, ansI; for (int i = 1; i <= n; i++) if (ansM < ceng[i]) { ansM = ceng[i]; ansI = i; } cout << ansI << endl; return 0; }