标签:des style class blog c code
Description
Input
Output
Sample Input
Sample Output
#include<map> #include<set> #include<stack> #include<queue> #include<cmath> #include<vector> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x0f0f0f0f using namespace std; const int maxn=40000+10; struct node { int c,v; }; vector<node>tree[maxn],que[maxn]; int num[maxn],dis[maxn],father[maxn]; bool mark[maxn],vis[maxn]; void init(int n) { for (int i=0;i<=n;i++) { tree[i].clear(); que[i].clear(); num[i]=0; vis[i]=0; mark[i]=0; father[i]=i; dis[i]=0; } } int find(int x) { return x==father[x]?x:father[x]=find(father[x]); } void Lca(int u) { father[u]=u; for (int i=0;i<tree[u].size();i++) { int v=tree[u][i].v; if (!mark[v]) { mark[v]=true; dis[v]=dis[u]+tree[u][i].c; Lca(v); father[v]=u; } } vis[u]=true; for (int i=0;i<que[u].size();i++) { int v=que[u][i].v; if (vis[v]) { num[que[u][i].c]=dis[u]+dis[v]-2*dis[find(v)]; } } } int main() { int t,n,m,x,y,c; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); init(n); for (int i=1;i<n;i++) { scanf("%d%d%d",&x,&y,&c); node temp; temp.c=c; temp.v=y; tree[x].push_back(temp); temp.v=x; tree[y].push_back(temp); } for (int i=0;i<m;i++) { scanf("%d%d",&x,&y); node temp; temp.v=y; temp.c=i; que[x].push_back(temp); temp.v=x; que[y].push_back(temp); } mark[1]=true; Lca(1); for (int i=0;i<m;i++) { printf("%d\n",num[i]); } //printf("\n"); } return 0; }
#include<map> #include<set> #include<stack> #include<queue> #include<cmath> #include<vector> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<iostream> #include<algorithm> #define inf 0x0f0f0f0f using namespace std; const int maxn=40000+10; struct node { int c,v; }; vector<node>tree[maxn],que[maxn]; int num[maxn],dis[maxn],father[maxn]; bool vis[maxn]; void init(int n) { for (int i=0;i<=n;i++) { tree[i].clear(); que[i].clear(); num[i]=0; vis[i]=0; father[i]=i; dis[i]=0; } } int find(int x) { return x==father[x]?x:father[x]=find(father[x]); } void Lca(int u) { father[u]=u; vis[u]=true; for (int i=0;i<que[u].size();i++) { int v=que[u][i].v; if (vis[v]) { num[que[u][i].c]=dis[u]+dis[v]-2*dis[find(v)]; } } for (int i=0;i<tree[u].size();i++) { int v=tree[u][i].v; if (!vis[v]) { dis[v]=dis[u]+tree[u][i].c; Lca(v); father[v]=u; } } } int main() { int t,n,m,x,y,c; scanf("%d",&t); while (t--) { scanf("%d%d",&n,&m); init(n); for (int i=1;i<n;i++) { scanf("%d%d%d",&x,&y,&c); node temp; temp.c=c; temp.v=y; tree[x].push_back(temp); temp.v=x; tree[y].push_back(temp); } for (int i=0;i<m;i++) { scanf("%d%d",&x,&y); node temp; temp.v=y; temp.c=i; que[x].push_back(temp); temp.v=x; que[y].push_back(temp); } Lca(1); for (int i=0;i<m;i++) { printf("%d\n",num[i]); } //printf("\n"); } return 0; }
hdu 2586 How far away ?,布布扣,bubuko.com
标签:des style class blog c code
原文地址:http://www.cnblogs.com/chensunrise/p/3751085.html