【最短路】 HDOJ 1317 XYZZY

spfa巧妙的变形。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 8005
#define maxm 8005
#define eps 1e-10
#define mod 998244353
#define INF 999999999
#define lowbit(x) (x&(-x))
#define mp mark_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid  
#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
// head

int h[maxn], next[maxm], v[maxm], cost[maxm];
int inq[maxn], dis[maxn], outq[maxn];
int in[maxn], vis[maxn];
queue<int> q;
int n, m, cnt;

void init(void)
{
	cnt = 0;
	memset(h, -1, sizeof h);
	memset(in, 0, sizeof in);
	memset(vis, 0, sizeof vis);
	memset(inq, 0, sizeof inq);
	memset(outq, 0, sizeof outq);
	for(int i = 0; i <= n; i++) dis[i] = -INF;
}
void addedges(int u, int vv, int c)
{
	next[cnt] = h[u], h[u] = cnt, v[cnt] = vv, cost[cnt] = c, cnt++;
}
void read(void)
{
	int a, b, c;
	for(a = 1; a <= n; a++) {
		scanf("%d%d", &c, &m);
		while(m--) scanf("%d", &b), addedges(a, b, c), in[b]++;
	}
}
bool spfa(int s)
{
	while(!q.empty()) q.pop();
	dis[s] = 100, q.push(s), inq[s] = 1;
	while(!q.empty()) {
		int u = q.front(); q.pop(), inq[u] = 0;
		if(outq[u] == n+1) continue;
		outq[u]++;
		if(outq[u] == n+1) dis[u] = INF;
		for(int e = h[u]; ~e; e = next[e])
			if(dis[v[e]] < dis[u] + cost[e] && dis[u] + cost[e] > 0) {
				if(v[e] == n) return true;
				dis[v[e]] = dis[u] + cost[e];
				if(!inq[v[e]]) inq[v[e]] = 1, q.push(v[e]);
			}
	}
	return false;
}
int main(void)
{
	while(scanf("%d", &n), ~n){
		init();
		read();
		if(spfa(1)) printf("winnable\n");
		else printf("hopeless\n");
	}
	return 0;
}


你可能感兴趣的:(HDU)