UVA 10557 XYZZY

来源:互联网 发布:双代号时标网络计划 编辑:程序博客网 时间:2024/06/05 08:20

题目

XYZZY

分析

  1. 有这样的一个游戏,游戏中有许多房间,开始时主角拥有100的体力,每进入一个房间都会消耗或增加房间对应的体力值,同时每个房间的出口不唯一,如果在到达最后一个房间前体力归零,GAME OVER && YOU LOST
  2. 显然主角应该尽可能地避免走入会消耗体力值的房间,如果无法避开,那么主角要有足够的体力值才可以尝试进入,可以发现如果有这么一个路连通两个或者多个房间能够不断恢复体力,那么可以意味着主角可以随意地 到任一房间也无妨,那么如果有并且能到达终点,胜利在望啊。
  3. 也就是说,对于连接房间()的路(),如果能够找到一个回复点(正环)且能够到达终点(可达)即可以判定胜利,如果找不到但是到达终点时仍有体力值,那么也可以判定为胜利。以外的情况均判定为失败

思路

  1. 首先考虑可达的问题,对于一张图,可以用邻接矩阵表示,也就是可以利用floyd_warshall()方法求其可达性矩阵,即可以判断两点是否可达。
  2. 举一个例子来意会一下bellman_ford()。对每一个点遍历一次边,松弛对应的权值的上界来满足经过该点时需要的负权。

5
0 1 2
20 2 1 3
-60 1 4
-60 1 5
0 0

那么它有这样五条边

(1 + 0)
1-> 2 +20
2 -> 1 +0
2 -> 3 -60
3 -> 4 -60
4 -> 5(终点) +0

松弛的结果如下

120 120 60 -100000000 -100000000
140 140 80 20 20
160 160 100 40 40
180 180 120 60 60
(+0)(+20)(-60)(-60)(+0)

样例

INPUT

4
0 1 2
-100 1 3
1 1 4
0 0
-1

OUTPUT

hopeless

代码

#include <cstdio>#include <cstring>#define MAX_V 105#define MAX_E MAX_V*MAX_V#define INF 100000000int A[MAX_V][MAX_V], d[MAX_V], cost[MAX_V];int V, E;struct edge { int from, to; } es[MAX_E], e;void input(){    E = 0;    memset(A, 0, sizeof(A));    int n = 0, t = 0;    for (int i = 1; i <= V; i++) {        scanf("%d%d", &cost[i], &n);        while (n--) {            scanf("%d", &t);            A[i][t] = 1; es[E].from = i; es[E].to = t; E++;        }    }}void floyd_warshall(){    for (int k = 1; k <= V; k++)        for (int i = 1; i <= V; i++)            for (int j = 1; j <= V; j++)                A[i][j] = A[i][j] | (A[i][k] & A[k][j]);}bool bellman_ford(){    for (int i = 1; i <= V; i++) d[i] = -INF;    d[1] = 100;    for (int i = 1; i < V; i++)        for (int j = 0; j < E; j++) {            e = es[j];            if (d[e.to] < d[e.from] + cost[e.to] && d[e.from] + cost[e.to] > 0)                d[e.to] = d[e.from] + cost[e.to];        }    for (int i = 0; i < E; i++) {        e = es[i];        if (d[e.to] < d[e.from] + cost[e.to] && d[e.from] + cost[e.to] > 0)            if (A[e.to][V]) return true;    }    return d[V] > 0;}void solve(){    floyd_warshall();    if (bellman_ford()) printf("winnable\n");    else printf("hopeless\n");}int main(){    while (scanf("%d", &V), V != -1) {        input();        solve();    }    return 0;}
0 0
原创粉丝点击