【差分约束+并查集】第十三届蓝桥杯省赛C++ A组 Java A组/研究生组《推导部分和》(C++)

【题目描述】

【输入格式】

【输出格式】

【数据范围】

【输入样例】

5 3 3
1 5 15
4 5 9
2 3 5
1 5
1 3
1 2

【输出样例】

15
6
UNKNOWN

【思路】

题解来源:AcWing 4651. $\Huge\color{gold}{推导部分和}$ - AcWing

【代码】

#include<bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define db double
#define int long long
#define PII pair<int,int >
#define mem(a,b) memset(a,b,sizeof(a))
#define IOS std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);

using namespace std;
const int mod = 1e9+7,inf = 1e18;
const int N = 2e5+10,M = 2010;

int T,n,m,k;
int va[N];
int acc[N];
int sum[N],vis[N];

vector<PII > e[N];

int find(int x)
{
    if(x!=acc[x]) acc[x] = find(acc[x]);
    return acc[x];
}

void bfs(int x)
{
    queue<int > q;
    q.push(x);
    sum[x] = 0,vis[x] = 1;
    while(q.size())
    {
        auto now = q.front();q.pop();
        for(auto t:e[now])
        {
            int spot = t.fi,w = t.se;
            if(vis[spot]) continue;
            vis[spot] = 1;
            sum[spot] = sum[now]+w;
            q.push(spot);
        }
    }
}

signed main()
{
    IOS;
    cin>>n>>m>>k;
    for(int i=0;i<=n;i++) acc[i] = i;
    while(m--)
    {
        int a,b,c;
        cin>>a>>b>>c;
        e[a-1].pb({b,c});
        e[b].pb({a-1,-c});
        acc[find(a-1)] = find(b);
    }
    for(int i=0;i<=n;i++) if(!vis[i]) bfs(i);
    while(k--)
    {
        int a,b;
        cin>>a>>b;
        if(find(a-1)!=find(b)) cout<<"UNKNOWN\n";
        else cout<<sum[b]-sum[a-1]<<"\n";
    }
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北洋的霞洛

觉得不确可以给个鼓励小费

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值