标签:scan rom sample line length -- problem ace use
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 14809 Accepted Submission(s): 5621
#include<iostream> #include<cstdio> #include<cmath> #include<map> #include<cstdlib> #include<vector> #include<set> #include<queue> #include<cstring> #include<string.h> #include<algorithm> typedef long long ll; typedef unsigned long long LL; using namespace std; const int N=40000+100; int head[N]; int vis[N]; int parent[N]; int ans[N]; int cnt; vector<int>q[N]; vector<int>Q[N]; int dis[N]; int n; int ancestor[N]; struct node{ int to,next,w; }edge[2*N+10]; void init(){ cnt=0; memset(ans,0,sizeof(ans)); memset(dis,0,sizeof(dis)); memset(head,-1,sizeof(head)); memset(vis,0,sizeof(vis)); for(int i=0;i<=n;i++){ parent[i]=i; Q[i].clear(); q[i].clear(); } } void add(int u,int v,int w){ edge[cnt].to=v; edge[cnt].w=w; edge[cnt].next=head[u]; head[u]=cnt++; } int find(int x){ int r=x; while(r!=parent[x])r=parent[r]; int i=x; int j; while(parent[i]!=r){ j=parent[i]; parent[i]=r; i=j; } return r; } void Union(int x,int y){ x=find(x); y=find(y); if(x!=y)parent[y]=x; } void Tarjan(int x,int w){ vis[x]=1; dis[x]=w; //cout<<dis[x]<<endl; for(int i=head[x];i!=-1;i=edge[i].next){ int v=edge[i].to; if(vis[v])continue; Tarjan(v,w+edge[i].w); Union(x,v); ancestor[find(x)]=x; } for(int i=0;i<q[x].size();i++){ int u=q[x][i]; if(vis[u]){ int t=ancestor[find(u)]; ans[Q[x][i]]=dis[x]+dis[u]-dis[t]*2; } } } int main(){ int m; int t; scanf("%d",&t); while(t--){ init(); scanf("%d%d",&n,&m); int u,v,w; for(int i=0;i<n-1;i++){ scanf("%d%d%d",&u,&v,&w); add(u,v,w); add(v,u,w); } for(int i=0;i<m;i++){ scanf("%d%d",&u,&v); q[u].push_back(v); q[v].push_back(u); Q[u].push_back(i); Q[v].push_back(i); } Tarjan(1,0); // for(int i=1;i<=n;i++)cout<<dis[i]<<" "; //cout<<endl; for(int i=0;i<m;i++){ // cout<<4<<endl; cout<<ans[i]<<endl; } } }
标签:scan rom sample line length -- problem ace use
原文地址:http://www.cnblogs.com/Aa1039510121/p/6657911.html