-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdaijkstra
104 lines (102 loc) · 1.99 KB
/
daijkstra
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
//파티
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#define MAX 1e8
using namespace std;
int N,M;
int X;
int dis[1001];
int dist[1001];
vector<pair<int,int>> adj[1001];
void dijkstra(int S){
fill(dis+1,dis+N+1,MAX);
priority_queue<pair<int,int>> pq;
dis[S]=0;
pq.push({0,S});
while(!pq.empty()){
int d=-pq.top().first;
int u=pq.top().second;
pq.pop();
if(d>dis[u]) continue;
for(int i=0;i<adj[u].size();i++){
int v=adj[u][i].first;
int c=adj[u][i].second;
if(dis[v]>dis[u]+c){
dis[v]=dis[u]+c;
pq.push({-dis[v],v});
}
}
}
}
int ans;
int main() {
ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin>>N>>M>>X;
for(int i=0,a,b,c;i<M;i++){
cin>>a>>b>>c;
adj[a].push_back({b,c});
}
for(int i=1;i<=N;i++){
dijkstra(i);
dist[i]=dis[X];
}
dijkstra(X);
for(int i=1;i<=N;i++) dist[i]+=dis[i];//cout<<dist[i];}
sort(dist+1,dist+N+1,greater<>());
cout<<dist[1];
return 0;
}
//음이 아닌 가중치 + 최단 경로
//1001 젤다
#include <iostream>
#include <queue>
#include <cstring>
#define MAX 100
using namespace std;
int dis[126][126]; int arr[126][126];
int dx[4]={1,0,-1,0};
int dy[4]={0,1,0,-1};
int N;
void dijkstra(){
memset(dis,MAX,sizeof(dis));
priority_queue<pair<int,pair<int,int>>>pq;
dis[0][0]=arr[0][0];
pq.push({arr[0][0],{0,0}});//거리, 정점
while(!pq.empty()){
int d=-pq.top().first;
int x=pq.top().second.first;
int y=pq.top().second.second;
cout<<d<<x<<y<<'\n';
pq.pop();
if(d>dis[x][y]) continue;
for(int i=0;i<4;i++){
int v=x+dx[i];
int z=y+dy[i];
if(v<0||z<0||v>=N||z>=N) continue;
int c=arr[v][z];
if(dis[v][z]>dis[x][y]+c){
dis[v][z]=dis[x][y]+c;
pq.push({-dis[v][z],{v,z}});
}
}
}
}
int main() {
int k=1;
while(true){
cin>>N;
if(N==0) break;
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
cin>>arr[i][j];
dijkstra();
for(int i=0;i<N;i++)
for(int j=0;j<N;j++)
cout<<dis[i][j];
cout<<"Problem "<<k<<": "<<dis[N-1][N-1]<<'\n';
k++;
}
return 0;
}