首页 > 其他分享 >推导部分和(图论)

推导部分和(图论)

时间:2023-02-12 12:22:51浏览次数:40  
标签:图论 推导 int ll color edge maxn now 部分

 

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
int n, m, q;
struct edge
{
    int v; ll w;
    edge(){}
    edge(int v, ll w):v(v), w(w){}
};
vector<edge>Map[maxn];
ll sum[maxn];
int color[maxn];

//从u出发,当前距离为d,当前连通块编号为 now_color
void dfs(int u, ll d, int now_color)
{
    color[u] = now_color;
    sum[u] = d;
    for(auto x : Map[u])
    {
        int v = x.v;
        ll w = x.w;
        if(color[v])continue;
        dfs(v, d + w, now_color);
    }
}

int main()
{
    cin >> n >> m >> q;
    for(int i = 1; i <= m; i++)
    {
        int l, r;
        ll s;
        cin >> l >> r >> s;
        //建图
        l--;
        Map[l].push_back(edge(r, s));
        Map[r].push_back(edge(l, -s));
    }
    int cnt = 0;//cnt表示连通块编号
    //每个连通块直接dfs
    for(int i = 0; i <= n; i++)if(color[i] == 0)
        dfs(i, 0, ++cnt);
    while(q--)
    {
        int l, r;
        cin >> l >> r;
        l--;
        if(color[l] != color[r])cout<<"UNKNOWN"<<endl;
        else cout<<sum[r] - sum[l]<<endl;
    }
    return 0;
}

 

标签:图论,推导,int,ll,color,edge,maxn,now,部分
From: https://www.cnblogs.com/weinan030416/p/17113628.html

相关文章