zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    CSS3实战:让我们尽情的圆角吧
    IE9、 Firefox、Safari, Chrome的CSS3圆角属性
    css清除浮动的几种方法整理
    display:inline-block的深入理解
    CSS display 属性详解
    ul 、ol li 继承原有样式的问题
    CSS的继承性
    CSS文档流与块级元素和内联元素(文档)
    HTML5 中的块级链接
    常用icon以及color颜色RGB值和对应颜色效果图
  • 原文地址:https://www.cnblogs.com/chendl111/p/8390492.html
Copyright © 2011-2022 走看看