AtCoder Beginner Contest 087 D People on a Line(DFS)
题意
给出n个点,m组关系L,R,D,L在R的左边距离D,判断是否存在n个人的位置满足m组关系
分析
Consider the following directed graph G:
There are N vertices numbered 1,2,...,N.
For each i, there are an edge from vertex Li to vertex Ri with weight Di, and an edge from vertex
Ri to vertex Li with weight −Di.
The problem asks whether we can assign an integer xv to each vertex v in G, such that for each edgefrom u to v with cost d, xv − xu = d holds. (Clearly, we can ignore the condition 0 ≤ xi ≤ 109.)
We handle each connected component in G independently. For each connected component, we choosean arbitary vertex v and assume that xv = 0. By running a dfs from v, we can uniquly determine thevalues of xi in this component. After that, we should check if the conditions are actually satisfied.
思路是建图+DFS
建图:对于L,R,D,L->D设置长度为D,R->L设置长度为-D
DFS:遍历每个联通块,对于一个点,若它被访问过,利用dis判断是否合法,若未被访问过,标记并dfs
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int n,m;
int L,R,D;
vector<pair<int,int> >mp[100100];
int dis[100100];
bool vis[100100];
int flag;
void dfs(int u,int pre)
{
if(!flag) return;
int sz=mp[u].size();
pair<int,int>tmp;
for(int i=0;i<sz;++i)
{
tmp=mp[u][i];
if(vis[tmp.first])
{
if(dis[u]+tmp.second!=dis[tmp.first])
{
flag=0;return;
}
}
else
{
vis[tmp.first]=1;
dis[tmp.first]=dis[u]+tmp.second;
dfs(tmp.first,u);
}
}
}
int main(int argc, char const *argv[])
{
/* code */
scanf("%d %d",&n,&m);
for(int i=1;i<=m;++i)
{
scanf("%d %d %d",&L,&R,&D);
mp[R].push_back(make_pair(L,D));
mp[L].push_back(make_pair(R,-D));
}
flag=1;
for(int i=1;i<=n;++i) if(!vis[i])
{
vis[i]=1;
dfs(i,-1);
}
if(flag) puts("Yes");else puts("No");
return 0;
}