Template + problem solving report: luogu P3385 [template] negative ring

Topic link: P3385 [template] negative ring
contraction point of the board.
Look Daily says \ (DFS \) will be fried (I did play the bombing), on the basis of his description \ (yy \) a \ (BFS \) , a multi-array to record the number of steps (I used \ (len [] \) ), if \ (len_i> the n-\) , it shows fled infinite loop in the negative, can return, I run faster than that page faster per capita \ (200ms \) like (not card Chang) (In fact, a bunch of Unshown).

\(Code\):

#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int inf=1e9;
int t,n,m,l,r,s;
int vis[2005],dis[2005];
int ans=0;
int len[2005];
struct node
{
    int to,nxt,w;
}e[2005<<1];
int head[2005],cnt=0;
queue<int> q;
void init(int n)
{
    while(!q.empty()) q.pop();
    memset(vis,0,sizeof(vis));
    memset(e,0,sizeof(e));
    memset(head,0,sizeof(head));
    for(int i=2;i<=n;i++) dis[i]=inf;
    dis[1]=0;
    vis[1]=1;
    len[1]=0;
    cnt=0;
}
void add(int u,int v,int c)
{
    e[++cnt].to=v;
    e[cnt].nxt=head[u];
    e[cnt].w=c;
    head[u]=cnt;
}
bool spfa()
{
    q.push(1);
    while(!q.empty())
    {
        int k=q.front();
        q.pop();
        vis[k]=0;
        for(int i=head[k];i;i=e[i].nxt)
        {
            int j=e[i].to;
            if(dis[j]>dis[k]+e[i].w)
            {
                dis[j]=dis[k]+e[i].w;
                len[j]=len[k]+1;
                if(len[j]>n) return true;
                if(!vis[j]) vis[j]=1,q.push(j);
            }
        }
    }
    return false;
}
int main()
{
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        init(n);
        for(int i=1;i<=m;i++)
        {
            scanf("%d%d%d",&l,&r,&s);
            add(l,r,s);
            if(s>=0) add(r,l,s);
        }
        if(spfa()) printf("YE5\n");
        else printf("N0\n"); 
    }
    return 0;
} 

Tucao about this "YE5" What is a ghost? Pull test words yeah ......

Guess you like

Origin www.cnblogs.com/tlx-blog/p/12318616.html