生活随笔
收集整理的這篇文章主要介紹了
P3385 【模板】负环
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
https://www.luogu.com.cn/problem/P3385
這個(gè)和普通的判負(fù)環(huán)有點(diǎn)區(qū)別。普通的判負(fù)環(huán)是判斷有沒有負(fù)環(huán)即可。
這個(gè)的判負(fù)環(huán)是從1出發(fā)的負(fù)環(huán)。
故得將距離初始化為無窮,然后只讓1入隊(duì)
#include<bits/stdc++.h>
using namespace std
;
const int N
=1e5*2+10;
int st
[N
],cnt
[N
],dist
[N
],t
,n
,m
,p
[N
];
int h
[N
],e
[N
],w
[N
],ne
[N
],idx
;
queue
<int>q
,temp
;
void init()
{q
=temp
;idx
=0;memset(h
,-1,sizeof h
);memset(st
,0,sizeof st
);memset(cnt
,0,sizeof cnt
);memset(dist
,0x3f,sizeof dist
);for(int i
=1;i
<=n
;i
++) p
[i
]=i
;
}
int find(int x
)
{if(x
!=p
[x
]) p
[x
]=find(p
[x
]);return p
[x
];
}
void add(int a
,int b
,int c
) {e
[idx
]=b
,w
[idx
]=c
,ne
[idx
]=h
[a
],h
[a
]=idx
++;}
bool spfa()
{q
.push(1),st
[1]=1,dist
[1]=0;while(q
.size()){int u
=q
.front(); q
.pop();st
[u
]=false;for(int i
=h
[u
];i
!=-1;i
=ne
[i
]){int j
=e
[i
];if(dist
[j
]>dist
[u
]+w
[i
]){dist
[j
]=dist
[u
]+w
[i
];cnt
[j
]=cnt
[u
]+1;if(cnt
[j
]>=n
) return true;if(!st
[j
]) q
.push(j
),st
[j
]=1;}}}return false;
}
int main(void)
{cin
>>t
;while(t
--){cin
>>n
>>m
;init();for(int i
=0;i
<m
;i
++){int a
,b
,c
; cin
>>a
>>b
>>c
;if(c
>=0) add(a
,b
,c
),add(b
,a
,c
);else add(a
,b
,c
);}if(spfa()) puts("YES");else puts("NO");}return 0;
}
總結(jié)
以上是生活随笔為你收集整理的P3385 【模板】负环的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。