I am really sorry for this code being so dirty. It's probably the worst I ever wrote. Sorry!
#include <iostream>
#include <vector>
#include <algorithm>
#include <bitset>
// #include <set>
using namespace std;
int n,best,worst;
vector<vector<int> > a;
vector<int> b,c,dist;
bitset<5001> vis;
int dfs(int u,bitset<5001> &vis,int dis){
if(vis[u]){
return dis-1;
}
vis[u]=1;
int ans=dis;
for(int i=0;i<a[u].size();i++){
ans=max(dfs(a[u][i],vis,dis+1),ans);
}
dist[u]=max(dis,dist[u]);
b[u]=max(b[u],dis);
c[u]=min(c[u],dis);
return ans;
}
int main(){
ios::sync_with_stdio(0);
while(ws(cin)&&!cin.eof()){
cin>>n;
a.assign(n+1,vector<int>());
// b.assign(n+1,0);
for(int i=1;i<=n;i++){
int j;
cin>>j;
while(j--){
int x;
cin>>x;
a[i].push_back(x);
}
}
best=0;
vis.reset();
b.assign(n+1,0);
c.assign(n+1,1e6);
dist.assign(n+1,0);
best=dfs(1,vis,0);
b.assign(n+1,0);
c.assign(n+1,1e6);
for(int i=1;i<=n;i++)
if(dist[i]==best){
vis.reset();
best=dfs(i,vis,0);
for(int j=1;j<=n;j++){
if(dist[j]==best&&j!=i){
vis.reset();
best=dfs(j,vis,0);
break;
}
}
break;
}
worst=best/2;
cout<<"Best Roots :";
for(int i=1;i<=n;i++)
if(b[i]==worst||((best&1)&&(b[i]==worst+1)))
cout<<' '<<i;
cout<<endl<<"Worst Roots :";
for(int i=1;i<=n;i++)
if(b[i]==best)
cout<<' '<<i;
cout<<endl;
}
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <bitset>
// #include <set>
using namespace std;
int n,best,worst;
vector<vector<int> > a;
vector<int> b,c,dist;
bitset<5001> vis;
int dfs(int u,bitset<5001> &vis,int dis){
if(vis[u]){
return dis-1;
}
vis[u]=1;
int ans=dis;
for(int i=0;i<a[u].size();i++){
ans=max(dfs(a[u][i],vis,dis+1),ans);
}
dist[u]=max(dis,dist[u]);
b[u]=max(b[u],dis);
c[u]=min(c[u],dis);
return ans;
}
int main(){
ios::sync_with_stdio(0);
while(ws(cin)&&!cin.eof()){
cin>>n;
a.assign(n+1,vector<int>());
// b.assign(n+1,0);
for(int i=1;i<=n;i++){
int j;
cin>>j;
while(j--){
int x;
cin>>x;
a[i].push_back(x);
}
}
best=0;
vis.reset();
b.assign(n+1,0);
c.assign(n+1,1e6);
dist.assign(n+1,0);
best=dfs(1,vis,0);
b.assign(n+1,0);
c.assign(n+1,1e6);
for(int i=1;i<=n;i++)
if(dist[i]==best){
vis.reset();
best=dfs(i,vis,0);
for(int j=1;j<=n;j++){
if(dist[j]==best&&j!=i){
vis.reset();
best=dfs(j,vis,0);
break;
}
}
break;
}
worst=best/2;
cout<<"Best Roots :";
for(int i=1;i<=n;i++)
if(b[i]==worst||((best&1)&&(b[i]==worst+1)))
cout<<' '<<i;
cout<<endl<<"Worst Roots :";
for(int i=1;i<=n;i++)
if(b[i]==best)
cout<<' '<<i;
cout<<endl;
}
}
Comments
Post a Comment