1 条题解
-
0
C++ :
#include <iostream> #include <algorithm> #include <queue> #define SIZE 1000 #define INF 1000000000 using namespace std; int n; int matrix[SIZE][SIZE]; int dis[SIZE], nums[SIZE]; bool inq[SIZE]; bool SPFA(int s) { fill(nums, nums + n, 0); fill(dis, dis + n, INF); fill(inq, inq + n, false); dis[s] = 0; queue<int> q; q.push(s); nums[s]++; inq[s] = true; int p; while (!q.empty()) { p = q.front(); q.pop(); inq[p] = false; for (int j = 0; j < n; j++) { if (matrix[p][j] != 0) { if (dis[p] + matrix[p][j] < dis[j]) { dis[j] = dis[p] + matrix[p][j]; if (false == inq[j]) { q.push(j); inq[j] = true; nums[j]++; if (nums[j] >= n) return false; } } } } } return true; } int main() { while (scanf("%d", &n) != EOF) { for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) scanf("%d", &matrix[i][j]); if (SPFA(0)) { for (int i = 1; i < n; i++) { printf("%d", dis[i]); if (i != n - 1) printf(" "); } } else printf("not possible"); printf("\n"); } return 0; }
Pascal :
var w:array[0..1000,0..1000]of integer; dist:array[0..1000]of integer; n,x,y,k,i,j,s:integer; change:boolean; begin readln(n); for i:=0 to n-1 do for j:=0 to n-1 do begin read(x); if (x=0)and(i<>j)then w[i,j]:=maxint else w[i,j]:=x; end; for i:=1 to n do if w[i,j]=maxint then dist[i]:=maxint else dist[i]:=w[0,i]; dist[0]:=0; for k:=1 to n-1 do for j:=0 to n-1 do for i:=0 to n-1 do if (w[i,j]<>maxint)and(dist[i]<>maxint)and(dist[j]>dist[i]+w[i,j]) then dist[j]:=dist[i]+w[i,j]; change:=true; for i:=0 to n-1 do for j:=0 to n-1 do if dist[j]>dist[i]+w[i,j] then change:=false; if change then begin for i:=1 to n-2 do write(dist[i],' '); write(dist[n-1]);end else writeln('not possible'); end.
- 1
信息
- ID
- 996
- 时间
- 1000ms
- 内存
- 128MiB
- 难度
- (无)
- 标签
- 递交数
- 0
- 已通过
- 0
- 上传者