标签:des style blog color java os strong io
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4477 Accepted Submission(s): 1284
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <vector> 5 #include <iostream> 6 using namespace std; 7 #define N 10005 8 9 struct node{ 10 int y, w; 11 }; 12 13 int f[N]; 14 int father[N]; 15 int dis[N]; 16 int visited[N]; 17 int ans[1000005]; //注意ans数组的大小,我就RE了很长时间。。。 18 vector<node>ve[N], q[N]; 19 int n; 20 21 void init(){ 22 for(int i=0;i<=n;i++){ 23 ve[i].clear(); 24 q[i].clear(); 25 f[i]=i; 26 father[i]=i; 27 } 28 memset(dis,0,sizeof(dis)); 29 memset(visited,0,sizeof(visited)); 30 memset(ans,-1,sizeof(ans)); 31 } 32 33 int findroot(int p){ 34 int r=p; 35 while(r!=father[r]) 36 r=father[r]; 37 return r; 38 } 39 void lca(int u,int d,int ff){ 40 int v, i; 41 node p; 42 visited[u]=1;dis[u]=d;f[u]=ff; 43 for(i=0;i<ve[u].size();i++){ 44 p=ve[u][i]; 45 v=p.y; 46 if(!visited[v]){ 47 lca(v,d+p.w,ff); 48 father[v]=u; 49 } 50 } 51 for(i=0;i<q[u].size();i++){ 52 p=q[u][i]; 53 int id=p.w; 54 v=p.y; 55 if(visited[v]&&f[v]==f[u]){ 56 ans[id]=dis[u]+dis[v]-2*dis[findroot(v)]; //findroot(v)而不是findroot(u),想一想为什么 57 } 58 } 59 } 60 main() 61 { 62 int m, Q; 63 int x, y, z; 64 int i, j, k; 65 node p; 66 while(scanf("%d %d %d",&n,&m,&Q)==3){ 67 init(); 68 for(i=0;i<m;i++){ 69 scanf("%d %d %d",&x,&y,&z); 70 p.y=y;p.w=z; 71 ve[x].push_back(p); 72 p.y=x; 73 ve[y].push_back(p); 74 } 75 for(i=1;i<=Q;i++){ 76 scanf("%d %d",&x,&y); 77 p.y=y;p.w=i; 78 q[x].push_back(p); 79 p.y=x; 80 q[y].push_back(p); 81 } 82 for(i=1;i<=n;i++){ 83 if(!visited[i]) 84 lca(i,0,i); 85 } 86 for(i=1;i<=Q;i++){ 87 if(ans[i]==-1) printf("Not connected\n"); 88 else printf("%d\n",ans[i]); 89 } 90 } 91 }
HDU 2874 LCA离线算法,布布扣,bubuko.com
标签:des style blog color java os strong io
原文地址:http://www.cnblogs.com/qq1012662902/p/3888675.html