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;
}

转载于:https://www.cnblogs.com/chendl111/p/8390492.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值