[ZJOI2012]旅游 对偶图 树的直径
Code:
// luogu-judger-enable-o2 #include<cstdio> #include<iostream> #include<algorithm> #include<map> #include<vector> #include<string> #include<cmath> using namespace std; void setIO(string a){ freopen((a+".in").c_str(),"r",stdin); freopen((a+".out").c_str(),"w",stdout); } void shutIO(){ fclose(stdin),fclose(stdout); } #define O2 __attribute__((optimize("-O3"))) #define maxn 300000 #define P pair<int,int> map<P,int>key; vector<int>G[maxn]; int idx,nodes,ans; O2 void insert(int a,int b,int i){ if(!key[P(a,b)]) key[P(a,b)]=key[P(b,a)]=++idx; int cur=key[P(a,b)]; G[cur].push_back(i); } int head[maxn], to[maxn<<1],nex[maxn<<1],cnt, d1[maxn],d2[maxn]; O2 void addedge(int u,int v){ nex[++cnt]=head[u],head[u]=cnt,to[cnt]=v; } O2 void dfs(int u,int fa){ d1[u]=d2[u]=0; for(int v=head[u];v;v=nex[v]){ if(to[v]==fa) continue; dfs(to[v],u); if(d1[to[v]]>d1[u]) d2[u]=d1[u],d1[u]=d1[to[v]]; else if(d1[to[v]]>d2[u]) d2[u]=d1[to[v]]; } ans=max(ans,d1[u]+d2[u]+1); ++d1[u],++d2[u]; } O2 int main(){ //setIO("shop"); int n; scanf("%d",&n); for(nodes=1;nodes<=n-2;++nodes){ int a,b,c; scanf("%d%d%d",&a,&b,&c); if(abs(a-b)!=1)insert(a,b,nodes); if(abs(a-c)!=1)insert(a,c,nodes); if(abs(b-c)!=1)insert(b,c,nodes); } for(int i=1;i<=idx;++i){ int siz=G[i].size()-1; for(int j=0;j<siz;++j) addedge(G[i][j],G[i][j+1]),addedge(G[i][j+1],G[i][j]); } dfs(1,0); printf("%d",ans); //shutIO(); return 0; }