蓝桥杯刷题记录
记录蓝桥杯刷题每一天
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 <stdio.h> #include <stdlib.h> 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; }