zoj 1053 FDNY to the Rescue!

此博客介绍了一款为纽约消防局设计的救援软件,该软件能够快速计算从各个消防站到达火灾现场所需的时间,并据此调度最近的消防站进行救援。
FDNY to the Rescue!
Time Limit: 2 Seconds      Memory Limit: 65536 KB

The Fire Department of New York (FDNY) has always been proud of their response time to fires in New York City, but they want to make their response time even better. To help them with their response time, they want to make sure that the dispatchers know the closest firehouse to any address in the city. You have been hired to write this software and are entrusted with maintaining the proud tradition of FDNY. Conceptually, the software will be given the address of the fire, the locations of the firehouses, street intersections, and the time it takes to cover the distance between each intersection. It will then use this information to calculate how long it takes to reach an address from each firehouse.

Given a specific fire location in the city, the software will calculate the time taken from all the fire stations located in the city to reach the fire location. The list of fire stations will be sorted from shortest time to longest time. The dispatcher can then pick the closest firestation with available firefighters and equipment to dispatch to the fire.


Input Format:

Line 1:
# of intersections in the city, a single integer (henceforth referred to as N) N<20

Lines 2 to N+1:
A table (square matrix of integer values separated by one or more spaces) representing the time taken in minutes between every pair of intersections in the city. In the sample input shown below the value ��3�� on the 1st row and the 2nd column represents the time taken from intersection #1 to reach intersection #2.

Similarly the value ��9�� on the 4th row and the 2nd column represents the time taken from intersection #4 to reach intersection #2.

A value of -1 for time means that it is not possible to go directly from the origin intersection (row #) to the destination intersection (column #). All other values in the table are non-negative.

Line N+2:
An integer value n (<= N) indicating the intersection closest to the fire location followed by one or more integer values for the intersections closest to the fire stations (all on one line, separated by one or more spaces) will follow the input matrix.

Notes on input format:

1. The rows and columns are numbered from 1 to N.
2. All input values are integers
3. All fire locations are guaranteed reachable from all firehouses.
4. All distance calculations are made from the intersection closest to each firehouse to the intersection closest to the fire.


Output Format:

Line 1:
A label line with the headings for each column, exactly as shown in the example.

Line 2 onwards (one line for each fire station):
A sorted list (based on time) showing the fire station (origin), the destination site, time taken and a complete shortest path of nodes from the originating fire station to the fire location.

Notes on output format:
1. Columns are tab separated.
2. If two or more firehouses are tied in time they can be printed in any order.
3. If more than one path exists that has the same minimal time for a given location & firehouse, either one can be printed on the output.
4. If the fire location and the fire station locations happen to be the same intersection, the output will indicate that the origin and destination have the same intersection number, the time will be ��0�� and the nodes in the shortest path will show just one number, the fire location.


This problem contains multiple test cases!

The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.

The output format consists of N output blocks. There is a blank line between output blocks.

 


Sample Input:

1

6
0 3 4 -1 -1 -1
-1 0 4 5 -1 -1
2 3 0 -1 -1 2
8 9 5 0 1 -1
7 2 1 -1 0 -1
5 -1 4 5 4 0
2 4 5 6

In the above input the last line indicates that ��2�� is the location of the fire and ��4��, ��5�� and ��6�� are the intersections where fire stations are located.


Sample Output:

Org     Dest    Time    Path
5       2       2       5       2
4       2       3       4       5       2
6       2       6       6       5       2 




//反向建边,然后求出最短路径、并打印路径
#include <iostream>
#include <stdio.h>
#include <queue>
#include <stack>
#include <set>
#include <vector>
#include <math.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define N 22
#define Max 1000000000
struct node
{
    int i;
    int dis;
    bool operator <(const node &b)const
    {
        return dis<b.dis;
    }
}st[N];
int n,s;
int map[N][N];
int f[N];
bool b[N];
int id;
int rc[N];
void deal(char *c)
{
    id=0;
    int i,t=0;
    for(i=0;c[i]!='\0';i++)//这题给的字符真是'\t'+'   '。。。。
    {
        if(c[i]>='0'&&c[i]<='9')
         t=t*10+c[i]-'0';
        else if(c[i-1]>='0'&&c[i-1]<='9')
         rc[id++]=t,t=0;
    }
    if(t) rc[id++]=t;
    s=rc[0];
    for(i=1;i<=n;i++)
      f[i]=s;
}
void dijskla()
{
    memset(b,0,sizeof(b));
    b[s]=1;
    int i,k,Min;
    int t=n;
    while(--t)
    {
           Min=Max;
        for(i=1;i<=n;i++)
         if(!b[i]&&Min>map[s][i])
          {
              Min=map[s][i];
              k=i;
          }
	if(Min==Max) break;//因为有些点不可达
        b[k]=1;
        for(i=1;i<=n;i++)
         if(!b[i]&&map[s][i]>map[s][k]+map[k][i])
	    f[i]=k,map[s][i]=map[s][k]+map[k][i];
		
    }
}
void output()
{
    int i,k=0,pr;
    for(i=1;i<id;k++,i++)
     st[k].i=rc[i],st[k].dis=map[s][rc[i]];
    sort(st,st+k);
    printf("Org\tDest\tTime\tPath\n");
    for(i=0;i<k;i++)
    {
        printf("%d\t%d\t%d",st[i].i,s,st[i].dis);
        pr=st[i].i;
        printf("\t%d",pr);
        while(pr!=f[pr])
        {
            pr=f[pr];
            printf("\t%d",pr);
        }
      printf("\n");
    }

}
char str[1000];
int main()
{
    
    int T,i,j;
	bool f=0;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(i=1;i<=n;i++)
           for(j=1;j<=n;j++)
	  {
	    scanf("%d",&map[i][j]);
	    if(map[i][j]==-1) map[i][j]=Max;
	  }
	for(i=1;i<=n;map[i][i]=0,i++)
	   for(j=i+1;j<=n;j++)
	      swap(map[i][j],map[j][i]);
	gets(str);
        gets(str); 
        deal(str);
        dijskla();
	if(f) printf("\n");else f=true;
        output();
    }
    return 0;
}

转载于:https://www.cnblogs.com/372465774y/archive/2012/11/19/2777552.html

### ZOJ 1500 Pre-Post-erous! 的解法分析 #### 题目解析 该问题的核心在于通过给定的一棵树的前序遍历和后序遍历来唯一确定一棵树,并计算其哈希值。输入中的 `N` 表示树的最大分支数量,而两个字符串分别表示前序遍历和后序遍历的结果。 为了构建唯一的二叉树结构并验证一致性,可以通过模拟的方式逐步重建树节点之间的父子关系[^4]。 --- #### 解决思路 1. **输入处理**: 将每组测试数据拆分为三部分:`N`, 前序序列 (`preorder`) 和 后序序列 (`postorder`)。 2. **合法性校验**: 判断前序和后序是否能够对应同一棵合法的树。如果无法匹配,则直接返回错误提示。 3. **树的重建**: 使用递归方式基于前序和后序来恢复树的结构。 - 前序的第一个字符总是根节点。 - 找到当前子树对应的范围,在后序中找到分割点以划分左子树和右子树。 4. **哈希值计算**: 对于每一颗子树,按照特定规则(如深度优先顺序)生成一个整数值作为最终输出。 以下是具体的 Python 实现: ```python def build_tree(preorder, postorder): if not preorder or not postorder: return None root_val = preorder[0] # 如果只有一个节点 if len(preorder) == 1: assert(postorder[0] == root_val) return (root_val,) # 寻找左右子树分界线 L = 1 while True: if set(preorder[1:L+1]) == set(postorder[:L]): break L += 1 left_pre = preorder[1:1+L] right_pre = preorder[L+1:] left_post = postorder[:L] right_post = postorder[L:-1] return ( root_val, build_tree(left_pre, left_post), build_tree(right_pre, right_post) ) def hash_tree(tree): if tree is None: return 0 elif isinstance(tree, tuple): # Non-leaf node _, left, right = tree return ((hash_tree(left) * 31 + ord(tree[0])) * 37 + hash_tree(right)) % 998244353 else: # Leaf node return ord(tree) def solve(): import sys input_data = sys.stdin.read().strip() lines = input_data.splitlines() results = [] i = 0 while i < len(lines): N_str = lines[i].split()[0] if N_str == '0': break N, pre_seq, post_seq = int(N_str), lines[i+1], lines[i+2] try: tree = build_tree(pre_seq, post_seq) result = hash_tree(tree) results.append(result) except AssertionError: results.append(0) i += 3 for res in results: print(res) # 调用函数解决问题 solve() ``` --- #### 关键点说明 1. **树的重建逻辑**: - 根据前序的第一个元素定位根节点。 - 在后序中查找与前序一致的部分,从而分离出左子树和右子树。 2. **哈希值计算**: - 左子树先被完全访问后再轮到右子树,最后加上根节点贡献。 - 结果取模 $998244353$ 来防止溢出。 3. **边界条件**: - 当遇到单节点或者空树时需特别注意判断。 --- #### 测试样例解释 对于样例输入: ``` 2 abc cba 2 abc bca 10 abc bca 13 abejkcfghid jkebfghicda 0 ``` 程序会逐一读入各组数据,调用上述算法完成树的重建以及哈希值计算,最终得到如下输出结果: ``` 4 1 45 207352860 ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值