-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlights.java
More file actions
114 lines (85 loc) · 2.82 KB
/
Flights.java
File metadata and controls
114 lines (85 loc) · 2.82 KB
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
105
106
107
108
109
110
111
112
113
114
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Flights {
public static class Pair {
int destination, distance;
public Pair(int destination, int distance) {
this.destination = destination;
this.distance = distance;
}
public int getFirst() {
return destination;
}
public int getSecond() {
return distance;
}
}
public static class Pair2{
int dest , cost ;
boolean used ;
public Pair2(int dest ,int cost , boolean used){
this.dest = dest;
this.cost = cost;
this.used = used;
}
public int getFirstp() {
return dest;
}
public int getSecondp() {
return cost;
}
public boolean getThirdp() {
return used;
}
}
HashMap<Integer, List<Pair>> adj = new HashMap<>();
int mini = Integer.MAX_VALUE; // Set to MAX_VALUE to find the minimum
public void addedge(int src, int dest, int distance) {
adj.putIfAbsent(src, new LinkedList<>());
adj.putIfAbsent(dest, new LinkedList<>());
adj.get(src).add(new Pair(dest, distance));
adj.get(dest).add(new Pair(src, distance));
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Flights f = new Flights();
int n = sc.nextInt();
int m = sc.nextInt();
for (int i = 0; i < m; i++) {
int src = sc.nextInt();
int dest = sc.nextInt();
int distance = sc.nextInt();
f.addedge(src - 1, dest - 1, distance); // Adjust to 0-based indexing
}
Queue<Pair2> q = new LinkedList<>();
int dist[][] = new int[n+1][1];
for(int i = 0; i <= n; i++){
Arrays.fill(dist,Integer.MAX_VALUE);
}
dist[1][0] = 0;
q.offer(new Pair2(1,0, false));
while(!q.isEmpty()){
Pair2 node = q.poll();
int dest = node.getFirstp();
int distance = node.getSecondp();
boolean flag = node.getThirdp();
if(distance > dist[dest][flag ? 1 : 0]){
continue;
}
for(Pair it : f.adj.get(dest)){
int ndestination = it.getFirst();
int ndistances = it.getSecond();
if(distance + ndistances < dist[ndestination][flag ? 1 : 0]){
dist[ndestination][flag ? 1 : 0] = distance + ndistances;
q.offer(new Pair2(ndestination, dist[ndestination][flag ? 1 : 0], flag));
}
if(!flag && ){
}
}
}
}
}