刷题记录-1蓝桥公园

蓝桥杯刷题记录

记录蓝桥杯刷题每一天


刷题记录-1蓝桥公园_第1张图片

刷题记录-1蓝桥公园_第2张图片
python解题

import sys

n, m, q = map(int, input().split())
dp = [[sys.maxsize]*(n+1) for _ in range(n+1)]

for _ in range(m):
    u, v, w = map(int, input().split())
    dp[u][v] = dp[v][u] = min(dp[u][v], w)

for k in range(1, n+1):
    for i in range(1, n+1):
        for j in range(1, n+1):
            if dp[i][k]+dp[k][j] < dp[i][j]:
                dp[i][j] = dp[i][k]+dp[k][j]

for _ in range(q):
    st, ed = map(int, input().split())
    if dp[st][ed] == sys.maxsize:
        print(-1)
    elif st == ed: print(0)
    else:
        print(dp[st][ed])

c解题

#include 
#include 
typedef long long ll;

#define N 402
ll map[N][N];

ll min(ll a,ll b){
  return a>b?b:a;
}

void init(int n,int m){
  int i,j;
  ll inf=4200000000;
  for(i=1;i<=n;i++){
    for(j=1;j<=n;j++){
      if(i==j) map[i][j]=0;
      else map[i][j]=inf;
    }
  }

  int u,v;
  ll w;
  while(m--){
    scanf("%d%d%lld",&u,&v,&w);
    map[u][v]=min(map[u][v],w);//防止重边
    map[v][u]=min(map[u][v],w);///切记时无向图,两边都要存
  }
  return ;
}

void floay(int n){
  int i,j,k;
  ll inf=4200000000;
  for(k=1;k<=n;k++){//在顶点如果使得更多的k作为中专点可以是i,j的距离更短,那么就用k去更新i,j
    for(i=1;i<=n;i++){
      for(j=1;j<=n;j++){
          if(map[i][k]<=inf&&map[k][j]<=inf&&map[i][j]>map[i][k]+map[k][j]){
            map[i][j]=map[i][k]+map[k][j];
          }
      }
    }
  }
  return ;
}

int main(int argc, char *argv[])
{
  // 请在此输入您的代码
  int n,m,q;
  ll inf=4200000000;
  scanf("%d%d%d",&n,&m,&q);
  init(n,m);
  floay(n);
  while(q--){
    int u,v;
    scanf("%d%d",&u,&v);
    if(map[u][v]<inf) printf("%lld\n",map[u][v]);
    else printf("-1\n");
  }
  return 0;
}

你可能感兴趣的:(刷题,python,程序人生)