【题目描述】
【输入格式】
【输出格式】
【数据范围】
【输入样例】
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;
}