标签:acm algorithm hihocoder lca tarjan
2 3 1 B A C A B C 3 2 B A C B A C C A
2 1 2
#include<map> #include<set> #include<cmath> #include<queue> #include<stack> #include<ctime> #include<string> #include<cctype> #include<cstdio> #include<cstdlib> #include<cstring> #include<iostream> #include<algorithm> using namespace std; typedef long long ll; typedef unsigned int uint; typedef unsigned long long ull; const int maxn = 1e5 + 5; const int maxv = 1e5 + 5; struct Edge{ int v,id; Edge(){} Edge(int v,int id){ this -> v = v; this -> id = id; } }; int T; int N,M,root; string name1,name2; int id,idx1,idx2; bool hasfa[maxn]; int father[maxn]; map<string,int>idx; vector<int>graph[maxn]; vector<Edge>edge[maxn]; int color[maxn],ans[maxn],depth[maxn]; pair<int,int>e[maxn]; bool vis[maxn]; int Find(int x){ return x!=father[x] ? father[x]=Find(father[x]) : father[x]; } int get_idx(string name){ if(idx.count(name)) return idx[name]; idx[name]=++id; return id; } /* void get_depth(int u,int dep){ depth[u]=dep; for(int i=0;i<graph[u].size();i++) get_depth(graph[u][i],dep+1); } */ void tarjan_LCA(int u){ color[u]=1; vis[u]=true; for(int i=0;i<edge[u].size();i++){ int ID=edge[u][i].id; if(ans[ID]) continue; int v=edge[u][i].v; if(color[v]==0) continue; if(color[v]==1) ans[ID]=v; if(color[v]==2) ans[ID]=Find(v); } for(int i=0;i<graph[u].size();i++){ int vv=graph[u][i]; if(!vis[vv]){ depth[vv]=depth[u]+1; tarjan_LCA(vv); color[vv]=2; father[vv]=u; } } } void init(){ for(int i=0;i<=maxn;i++){ graph[i].clear(); edge[i].clear(); father[i]=i; hasfa[i]=vis[i]=false; ans[i]=color[i]=depth[i]=0; } idx.clear(); id=0; root=0; } void input(){ scanf("%d%d",&N,&M); for(int i=1;i<N;i++){ cin>>name1>>name2; idx1=get_idx(name1); idx2=get_idx(name2); graph[idx2].push_back(idx1); hasfa[idx1]=true; } for(int i=1;i<=M;i++){ cin>>name1>>name2; idx1=get_idx(name1); idx2=get_idx(name2); e[i].first=idx1; e[i].second=idx2; edge[idx1].push_back(Edge(idx2,i)); edge[idx2].push_back(Edge(idx1,i)); } } void solve(){ for(int i=1;i<=N;i++){ if(!hasfa[i]){ root=i; break; } } tarjan_LCA(root); for(int i=1;i<=M;i++){ int sum=depth[e[i].first]-depth[ans[i]]; if(e[i].second!=ans[i]) sum++; if(e[i].first==e[i].second) sum=0; printf("%d\n",sum); } } int main(){ scanf("%d",&T); while(T--){ init(); input(); solve(); }return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:acm algorithm hihocoder lca tarjan
原文地址:http://blog.csdn.net/jhgkjhg_ugtdk77/article/details/47207881