HDU 2923 Einbahnstrasse(两种方法)

本文探讨了在一个一维街道模型中寻找从公司到故障车辆所在地并返回的最短路径问题,提供了两种解决方法:使用Floyd算法和Dijkstra算法,并附上了相应的AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
Einbahnstra e (German for a one-way street) is a street on which vehicles should only move in one direction. One reason for having one-way streets is to facilitate a smoother flow of traffic through crowded areas. This is useful in city centers, especially old cities like Cairo and Damascus. Careful planning guarantees that you can get to any location starting from any point. Nevertheless, drivers must carefully plan their route in order to avoid prolonging their trip due to one-way streets. Experienced drivers know that there are multiple paths to travel between any two locations. Not only that, there might be multiple roads between the same two locations. Knowing the shortest way between any two locations is a must! This is even more important when driving vehicles that are hard to maneuver (garbage trucks, towing trucks, etc.)

You just started a new job at a car-towing company. The company has a number of towing trucks parked at the company's garage. A tow-truck lifts the front or back wheels of a broken car in order to pull it straight back to the company's garage. You receive calls from various parts of the city about broken cars that need to be towed. The cars have to be towed in the same order as you receive the calls. Your job is to advise the tow-truck drivers regarding the shortest way in order to collect all broken cars back in to the company's garage. At the end of the day, you have to report to the management the total distance traveled by the trucks.


Input
Your program will be tested on one or more test cases. The first line of each test case specifies three numbers (N , C , and R ) separated by one or more spaces. The city has N locations with distinct names, including the company's garage. C is the number of broken cars. R is the number of roads in the city. Note that 0 < N < 100 , 0<=C < 1000 , and R < 10000 . The second line is made of C + 1 words, the first being the location of the company's garage, and the rest being the locations of the broken cars. A location is a word made of 10 letters or less. Letter case is significant. After the second line, there will be exactly R lines, each describing a road. A road is described using one of these three formats:


A -v -> B
A <-v - B
A <-v -> B


A and B are names of two different locations, while v is a positive integer (not exceeding 1000) denoting the length of the road. The first format specifies a one-way street from location A to B , the second specifies a one-way street from B to A , while the last specifies a two-way street between them. A , ``the arrow", and B are separated by one or more spaces. The end of the test cases is specified with a line having three zeros (for N , C , and R .)

The test case in the example below is the same as the one in the figure.



Output
For each test case, print the total distance traveled using the following format:


k . V


Where k is test case number (starting at 1,) is a space, and V is the result.


Sample Input

4 2 5
NewTroy Midvale Metrodale
NewTroy <-20-> Midvale
Midvale --50-> Bakerline
NewTroy <-5-- Bakerline
Metrodale <-30-> NewTroy
Metrodale --5-> Bakerline
0 0 0



Sample Output

1. 80



题意:从公司去车坏的地方,然后再从车坏的地方回来,问最少的花费是多少

有两种方法:

1.floyd

利用map容器我把各个地方都映射为一个点,然后再求一个点到一个点的最短路即可。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
#define INF 0x3f3f3f3f
#define MAX 1000
using namespace std;
int vis[MAX],dis[MAX];
int map1[MAX][MAX];
char rr[1001][100];
int n,m,C;
void floyd()
{
    for(int k = 1; k <= n; k++)
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                if(map1[i][j] > map1[i][k]+map1[k][j])
                    map1[i][j] = map1[i][k]+map1[k][j];

}
int main()
{
    int case1 = 1;
    while(~scanf("%d%d%d",&n,&C,&m))
    {
        if(n==0&&C==0&&m==0)
            break;
        map<string,int>s;
        int ans = 1;
        s.clear();
        for(int i = 0; i <= C; i++)
        {
            scanf("%s",rr[i]);
            if(rr[i]==0)
                s[rr[i]] = ans++;
        }
        for(int i = 0; i < 110; i++)
        {
            for(int j = 0; j < 110; j++)
                map1[i][j] = INF;
            map1[i][i] = 0;
        }
        char p[31],q[31];
        char a[31];
        for(int i = 0; i < m; i++)
        {
            scanf("%s%s%s",p,a,q);
            if(!s[p]) s[p] = ans++;
            if(!s[q]) s[q] = ans++;
            int len = strlen(a);
            int value = 0,flag = 1;
            for(int j = len - 3; j > 1; j--)
            {
                value+=(a[j] - 48)*flag;
                flag*=10;
            }
            if(map1[s[p]][s[q]] > value&&a[0] == '<')
                map1[s[p]][s[q]] = value;
            if(map1[s[q]][s[p]] > value&&a[len-1] == '>')
                map1[s[q]][s[p]] = value;
        }
        /**for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < n; j++)
                printf("%d ",map1[i][j]);
            printf("\n");
        }*/
        /**printf("%d. ",case1++);
        floyd();
        int sum = 0;
        for(int i = 1; i <= C; i++)
        {
            sum+=map1[s[rr[0]]][s[rr[i]]] + map1[s[rr[i]]][s[rr[0]]];
        }
        printf("%d\n",sum);
    }
    return 0;
}

2.dijkstra

首先创建一个数组Map[MAXN][MAXN][k],当k = 0时,是正向图,k = 1时, 是反向图。然后我每次都找从1到任意点的最短路径即可。

AC代码:

#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<cstring>
#include<string>
#include<stack>
#include<map>
#include<set>
#define INF 0x3f3f3f3f
#define MAXN 1002

using namespace std;

int Map[MAXN][MAXN][2];
///Map[MAXN][MAXN][0]用来存放正向图,Map[MAXN][MAXN][1]用来存放反向图
int dis[MAXN][2],vis[MAXN];
///dis[MAXN][0]用来存放正向图,节点1到各个点的最短路径;
///dis[MAXN][1]用来存放反向图,求节点1到各个点的最短路径。相当于求各个点到1的最短路径。
//is用来标记的
int N,C,R;
void InitMap()  ///初始化地图,完全正确
{
   for(int k = 0; k < 2; k++)
   {
       for(int i = 1; i <= N; i++)
       {
            Map[i][i][k] = 0;
            for(int j = i+1; j <= N; j++)
                Map[i][j][k] = Map[j][i][k] = INF;
       }
   }
}
void Dijkstra(int a)  ///参数a代表求那个图的最短路径,0代表求原图,1代表求反图
{
    int mindis,u;
    for(int i = 1; i <= N; i++)
    {
        vis[i] = 0;
        dis[i][a] = Map[1][i][a];
    }
    vis[1] = 1;
    for(int i = 1; i <= N; i++)
    {
        mindis = INF;
        u = 0;
        for(int j = 1; j <= N; j++)
        {
            if(vis[j]==0 && dis[j][a]<mindis)
            {
                u = j;
                mindis = dis[j][a];
            }
        }
        if(u == 0) break;
        vis[u] = 1;
        for(int j = 1; j <= N; j++)
        {
            if(vis[j]==0)
            {
                if(dis[u][a]+Map[u][j][a]<dis[j][a])
                {
                    dis[j][a] = dis[u][a]+Map[u][j][a];
                }
            }
        }
    }
}
int main()
{
    int t = 0;
    while(~scanf("%d%d%d",&N,&C,&R)) ///N是location的个数,C是出故障的车的数目,R是直通道路条数
    {
        if(N==0 && C==0 && R==0) break;  ///程序结束条件
        InitMap();                       ///完成图的初始化工作
        map<string,int>m;
        vector<int>v;
        char pos1[12],pos2[12],dist[50];
        int num = 0;
        for(int i = 0; i <= C; i++)
        {
            scanf("%s",pos1);  ///输入城市。
            if(!m[pos1])
            {
                m[pos1] = (++num);
            }
            v.push_back(m[pos1]);
        }
        int _go,_back,sub1,sub2,_dist;
        for(int i = 0; i < R; i++)
        {
            _go = _back = _dist = 0;
            scanf("%s%s%s",pos1,dist,pos2);
            if(!m[pos1]) m[pos1] = (++num);
            sub1 = m[pos1];
            if(!m[pos2]) m[pos2] = (++num);
            sub2 = m[pos2];
            for(int j = 0; j < strlen(dist); j++)
            {
                if(dist[j]=='>')
                    _go = 1;
                if(dist[j]=='<')
                    _back = 1;
                if(dist[j]>='0'&&dist[j]<='9')
                    _dist = _dist*10 + (dist[j]-'0');
            }
            if(_go)  ///sub1到sub2有路
            {
                if(_dist < Map[sub1][sub2][0])
                {
                    Map[sub1][sub2][0] = _dist;
                    Map[sub2][sub1][1] = _dist;
                }
            }
            if(_back)  ///sub2到sub1有路
            {
                if(_dist < Map[sub2][sub1][0])
                {
                    Map[sub2][sub1][0] = _dist;
                    Map[sub1][sub2][1] = _dist;
                }
            }
        }
        Dijkstra(0);
        Dijkstra(1);
        int ans = 0;
        for(int i = 0; i < v.size(); i++)
        {
            ans = ans + dis[v[i]][0] + dis[v[i]][1];
        }
        printf("%d. %d\n",++t,ans);
    }
    return 0;
}


HDU(Hangzhou Dianzi University)OJ 中经常涉及到几何计算的问题,其中“判断两条线段是否相交”是一个经典的算法问题。以下是关于如何判断两线段是否相交的基本思路及其实现步骤: ### 判断两条线段相交的核心思想 可以利用向量叉积以及端点位置的关系来确定两条线段是否相交。 #### 具体步骤: 1. **定义基本概念** - 假设两条线段分别为 `AB` 和 `CD`。 - 使用二维平面中的坐标表示各顶点:A(x₁,y₁), B(x₂,y₂),C(x₃,y₃) ,D(x₄,y₄)。 2. **叉积的作用** 叉积可以帮助我们了解两点相对于一条直线的位置关系。 对于三个点 P、Q、R ,我们可以用叉乘 `(Q-P)x(R-P)` 来检测 R 是否在 QP 直线的一侧还是另一侧。 如果结果为正数,则表明顺时针;如果负则逆时针;若等于0则共线。 3. **快速排斥实验** 首先做一个矩形包围盒测试——即检查两个线段所在的最小外接矩形是否有重叠区域。如果没有重叠直接判定为不相交。 4. **跨立试验 (Cross-over Test)** 确认每个线段的两端分别位于另一个线段两侧即可认为它们交叉了。这通过上述提到过的叉积运算完成。 5. **特殊情况处理** 包含但不限于如下的几种情况需要单独讨论: - 完全重合的部分; - 存在一个公共端点但并不完全穿过等边缘状况。 6. **代码框架示例(Pseudo code):** ```python def cross_product(p1,p2,p3): return (p2[0]-p1[0])*(p3[1]-p1[1])-(p2[1]-p1[1])*(p3[0]-p1[0]) def on_segment(p,q,r): if ((q[0] <= max(p[0], r[0])) and (q[0] >= min(p[0], r[0])) and (q[1] <= max(p[1], r[1])) and (q[1] >= min(p[1], r[1]))): return True; return False; def do_segments_intersect(A,B,C,D): # 计算四个方向的叉积值 o1 = cross_product(A, C, B) o2 = cross_product(A, D, B) o3 = cross_product(C, A, D) o4 = cross_product(C, B, D) # 标准情况判断 if(o1 !=o2 && o3!=o4): return True # 特殊情况逐一验证... ``` 7. 最终结合所有条件得出结论。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值