题解:P1001 A+B Problem

· · 题解

前言

考虑把题目转化为图上问题:相当于三个节点(记作 1,2,3),连一条从 1 至 2,权值为 a 的边;以及一条从 2 至 3,权值为 b 的边。答案就是从 1 到 3 的最短路。

我们发现边的数量和点的数量很少,考虑 Floyd。时间复杂度为 O(n^3),时间还是卡得很死的。

代码

#include<bits/stdc++.h>
#define ll long long
#define endl '\n'
using namespace std;
int a,b;
int G[5005][5005];//邻接矩阵存图
signed main(int argc,char *argv[]){
//  freopen(".in","r",stdin);
//  freopen(".out","w",stdout);
    ios::sync_with_stdio(NULL);
    cin.tie(0),cout.tie(0);
    cin>>a>>b;
    //初始化为极大值 
    for(int i=1;i<=5000;i++){
        for(int j=1;j<=5000;j++){
            G[i][j]=2147483647;
        } 
    }
    G[1][2]=a;//建边 
    G[2][3]=b;
    //Floyd
    for(int k=1;k<=3;k++){
        for(int i=1;i<=3;i++){
            for(int j=1;j<=3;j++){
                G[i][j]=min(G[i][j],G[i][k]+G[k][j]);//松弛 
            }
        }
    }
    cout<<G[1][3]<<endl;//直接输出最短路 
    return 0;
}
/*
---INFORMATIONS---
TIME:2025/5/10 14:10:44
PROBLEM:P1001
CODE BY __CrossBow_EXE__ Luogu uid967841
*/