CHEFPRES
所谓一眼题,但是通过这道题学了c++的vector...
只想表示学语言什么的看别人代码最快了。。不想啃书
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <vector> #include <algorithm> using namespace std; #define MAXN 100010 #define MAXK 110 vector<int> a[MAXK]; struct node{ int y,next; }edge[MAXN]; int f[MAXN][20]; int head[MAXN],deep[MAXN]; bool vis[MAXN]; int n,l,x,y,k,b,lfather,ans,ans1,st,q,p,sa; void add(int x,int y) { l++; edge[l].y=y; edge[l].next=head[x]; head[x]=l; } void dfs(int x) { vis[x]=1; for (int i=head[x];i>0;i=edge[i].next) { if (!vis[edge[i].y]) { deep[edge[i].y]=deep[x]+1; f[edge[i].y][0]=x;//pre的一部分 dfs(edge[i].y); } } } void pre() { for (int j=1;j<=17;j++) for (int i=1;i<=n;i++) f[i][j]=f[f[i][j-1]][j-1]; } int lca(int x,int y) { if (x==y) return x; if (deep[x]>deep[y]) { int t=x;x=y;y=t; } for (int i=17;i>=0;i--) if (deep[f[y][i]]>=deep[x]) y=f[y][i]; if (x==y) return x;//!! for (int i=17;i>=0;i--) if (f[x][i]!=f[y][i]) { x=f[x][i]; y=f[y][i]; } return f[x][0]; } int main() { l=0; scanf("%d%d%d", &n, &k, &b); memset(head,0,sizeof(head)); for (int i=1;i<=n-1;i++) { scanf("%d%d", &x, &y); add(x,y); add(y,x); } for (int i=1;i<=n;i++) { scanf("%d", &x); a[x].push_back(i); } for (int i=1;i<=k;i++) sort(a[i].begin(),a[i].end());//** memset(vis,0,sizeof(vis)); deep[b]=1; dfs(b); pre(); scanf("%d",&q); while (q--) { scanf("%d%d", &sa, &p); if (a[p].size()==0) printf("%d\n",-1); else { ans=0; for (int i=0;i<a[p].size();i++)//注意这里从0开始啦~ { st=a[p][i];//像数组一样取数~ lfather=lca(sa,st); if (deep[lfather]>ans) { ans=deep[lfather]; ans1=st; } } printf("%d\n",ans1); } } return 0; }