跳到正文

题解

AT_abc373_d 题解

ikunTLE约 2 分钟
原文
文章信息与版本

文章信息

发布
2024年10月1日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟
获赞
12

版本

  1. v1当前

题目传送门

思路

如果确定了一个顶点的值,相邻顶点的值确定。由于该图的连通性,只要任意一点上的值确定,所有的值都会根据该点得知而确定。

因此,可以给初始的顶点赋值为 00,BFS 确定其连通的值。

注意事项

  • 不开 long long 见祖宗。

AC CODE

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
int read(){int x=0;char f=1,ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();return x*f;}
const int N=2e5+10;
struct node{
	int v,w;
};vector<node>vc[N];
bool vis[N];
int ans[N];
signed main(){
	int n=read(),m=read();
	while(m--){
		int u=read(),v=read(),w=read();
		vc[u].push_back({v,w});
		vc[v].push_back({u,-w});
	}
	for(int i=1;i<=n;++i){
		if(vis[i])
			continue;
		queue<int>q;
		q.push(i),vis[i]=true;
		while(!q.empty()){
			int u=q.front();
			for(auto i:vc[u])
				if(!vis[i.v]){
					vis[i.v]=true;
					ans[i.v]=ans[u]+i.w;
					q.push(i.v);
				}
			q.pop();
		}
	}
	for(int i=1;i<=n;++i)
		printf("%lld ",ans[i]);
	printf("\n");
	return 0;
}
原文