欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 创投人物 > 推导部分和-图论+dfs+连通块

推导部分和-图论+dfs+连通块

2025/7/26 0:43:20 来源:https://blog.csdn.net/2301_80422662/article/details/147743739  浏览:    关键词:推导部分和-图论+dfs+连通块

先研究一下,感觉有点像lca里的树上前缀和,不过树有多颗,用color区分一下

https://www.luogu.com.cn/problem/P8779

#include<bits/stdc++.h>
using namespace std;
#define N 100011
typedef  long long ll;
typedef pair<int,int> pii;
int n,k,m,cnt;
typedef struct edge
{int v;ll w;
}edge ;
vector<edge> mp[N];
int color[N];
ll pre_sum[N];///前缀和 
void dfs(int u,ll d,int cnt)///树上前缀和的思路,color标记不同的树 
{pre_sum[u]=d;color[u]=cnt;for(auto a:mp[u]){int v=a.v;ll w=a.w;if(color[v]) continue;dfs(v,d+w,cnt);}
}
int main()
{ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);cin>>n>>m>>k;for(int i=0;i<m;i++){int u,v;ll w;cin>>u>>v>>w;mp[u-1].push_back({v,w});///0-5时正的 mp[v].push_back({u-1,-1*w});///5-0是负的 }for(int i=1;i<=n;i++){if(!color[i]){dfs(i,0,++cnt); ///Color来标记和区分不同树 }}while(k--){int l,r;cin>>l>>r;if(color[l-1]!=color[r]) cout<<"UNKNOWN"<<endl;///不在同一棵树 else{cout<<pre_sum[r]-pre_sum[l-1]<<endl;///区间和用树上前缀和来求 }}return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词