UVA10557 XYZZY 题解
题解索引
- 题目大意
- Solution
- AC code
- 类似题型
代码类型: C++(cpp)
是否吸氧:否
不压行代码长度:57
题目大意
题面: <传送门>
题意:给一个张
可能有 负环 ,且点
术语理解:负环板子题。
Solution
负环板子,还需要讲?
判负环方式:
-
当这个节点的循环次数(被处理次数)
>n (一个点最多被n-1 条边连着,前提是无重边无自环)即为死循环 -
我们将最短路线看为一棵树(最短路树),每找到一个点深度就加一(从
u 至v ,把v 视为u 的子树)
本题解选用方式 1 进行判负环。
当然了,注意使用的最短路算法要能跑负权,比如 spfa 。
AC code
#include<iostream>
#include<cstdio>
#include<cmath>
#include<queue>
#include<cstring>
using namespace std;
const int MAXM=2e6+9,MAXN=1e6+9;
struct Edge{
int nxt,to,w;
}edge[MAXM];
int num_edge=0,head[MAXN],dis[MAXN],dep[MAXN];
bool vis[MAXN];
int n;
void add_edge(int from,int to,int w){
edge[++num_edge]=(Edge){head[from],to,w};
head[from]=num_edge;
}bool spfa(int s){
queue<int>q;
memset(dis,0,sizeof(dis));
memset(vis,0,sizeof(vis));
memset(dep,0,sizeof(dep));
q.push(s);
dis[s]=100;
vis[s]=1;
while(!q.empty()){
int x=q.front();
q.pop();
vis[x]=0;
for(int i=head[x];i;i=edge[i].nxt){
int to=edge[i].to;
if(dep[to]>n*100)return false;
if(dis[to]<dis[x]+edge[i].w){
dep[to]++;
dis[to]=dis[x]+edge[i].w;
if(!vis[to])q.push(to),vis[to]=1;
}
}if(dis[n]>0)return true;
}return false;
}
int main(){
while(scanf("%d",&n)&&n!=-1){
num_edge=0;
memset(head,0,sizeof(head));
for(int i=1;i<=n;i++){
int w,num;
scanf("%d %d",&w,&num);
while(num--){
int to;
scanf("%d",&to);
add_edge(i,to,w);
}
}if(spfa(1))printf("winnable\n");
else printf("hopeless\n");
}
return 0;
}
AC记录<传送门>
类似题型
P3385 【模板】负环