zoukankan      html  css  js  c++  java
  • P3385 【模板】负环


    P3385 【模板】负环



    时间限制 2.00s
    内存限制 256.00MB


    题目描述


    给定一个 nnn 个点的有向图,请求出图中是否存在从顶点\(1\)出发能到达的负环。

    负环的定义是:一条边权之和为负数的回路。


    输入格式


    本题单测试点有多组测试数据

    输入的第一行是一个整数\(T\),表示测试数据的组数。对于每组数据的格式如下:

    第一行有两个整数,分别表示图的点数\(n\)和接下来给出边信息的条数\(m\)

    接下来\(m\)行,每行三个整数\(u,v,w\)

    • \(w \geq 0\),则表示存在一条从\(u\)\(v\)边权为\(w\)的边,还存在一条从\(v\)\(u\)边权为\(w\)的边。
    • \(w < 0\),则只表示存在一条从\(u\)\(v\)边权为\(w\)的边。

    输出格式


    对于每组数据,输出一行一个字符串,若所求负环存在,则输出 YES,否则输出 NO


    输入输出样例


    输入 #1

    2
    3 4
    1 2 2
    1 3 4
    2 3 1
    3 1 -3
    3 3
    1 2 3
    2 3 4
    3 1 -8
    

    输出 #1

    NO
    YES
    

    说明/提示

    数据规模与约定

    对于全部的测试点,保证:

    • \(1 \leq n \leq 2 \times 10^3, \; 1 \leq m \leq 3 \times 10^3\)
    • \(1 \leq u, v \leq n, \; -10^4 \leq w \leq 10^4\)
    • \(1 \leq T \leq 10\)

    提示

    请注意,\(m\)不是图的边数。




    代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<queue>
    #include<vector>
    using namespace std;
    const int N=3e3+5;
    int n,m,cnt[N],dis[N];
    bool vis[N];
    vector<int>E[N],W[N];
    bool spfa(){
    	memset(vis,0,sizeof(vis));
    	memset(cnt,0,sizeof(cnt));
    	memset(dis,0x7f,sizeof(dis));
    	queue<int>q;
    	dis[1]=0; q.push(1); vis[1]=1;
    	while(!q.empty()){
    		int u=q.front(); q.pop(); vis[u]=0;
    		for(int v,w,i=0;i<E[u].size();++i){
    			v=E[u][i]; w=W[u][i];
    			if(dis[v]>dis[u]+w){
    				cnt[v]=cnt[u]+1; if(cnt[v]>=n) return 0;
    				dis[v]=dis[u]+w;
    				if(!vis[v]){ q.push(v); vis[v]=1; }
    			}
    		}
    	}
    	return 1;
    }
    int main(){
    	int T; scanf("%d",&T); while(T--){
    		scanf("%d %d",&n,&m);
    		for(int i=1;i<=n;++i) E[i].clear(),W[i].clear();
    		while(m--){
    			int u,v,w;
    			scanf("%d %d %d",&u,&v,&w);
    			E[u].push_back(v);
    			W[u].push_back(w);
    			if(w>=0){
    				E[v].push_back(u);
    				W[v].push_back(w);
    			}
    		}
    		if(spfa()) puts("NO");
    		else puts("YES");
    	}
    	return 0;
    }
    
  • 相关阅读:
    每天一道LeetCode--141.Linked List Cycle(链表环问题)
    每天一道LeetCode--119.Pascal's Triangle II(杨辉三角)
    每天一道LeetCode--118. Pascal's Triangle(杨辉三角)
    CF1277D Let's Play the Words?
    CF1281B Azamon Web Services
    CF1197D Yet Another Subarray Problem
    CF1237D Balanced Playlist
    CF1239A Ivan the Fool and the Probability Theory
    CF1223D Sequence Sorting
    CF1228D Complete Tripartite
  • 原文地址:https://www.cnblogs.com/Potrem/p/Luogu_P3385.html
Copyright © 2011-2022 走看看