Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- There is a source (S) and destination (D) and a spacecraft has to go from S to D. There are N number of wormholes in between which has following properties:
- Each wormhole has an entry and an exit. Each wormhole is bi-directional i.e. one can enter and exit from any of the ends. The time to cross the wormhole is given and the space craft may or may not use the wormhole to reach D. The time taken to travel outside wormhole between two points (x1, y1) and (x2, y2) is given by a formula |x1 - x2| + |y1 - y2|
- where, (x1, y1) and (x2, y2) are the co-ordinates of two points. The co-ordinates of S and D are given and we have to find the minimum time to reach D from S.
- Note: Itβs not mandatory to consider all the wormholes.
- */
- #include <iostream>
- using namespace std;
- struct point{
- int x,y;
- }src,dest;
- struct wormhole{
- int s1,s2,d1,d2,cost;
- }worm[100];
- int findDistance(point a, point b){
- return abs(a.x-b.x) + abs(a.y -b.y);
- }
- int n;
- int visited[100]={false};
- int ans;
- void solve(point cur_pos, int cost, int worm_left ){
- ans=min(ans,cost + findDistance(cur_pos,dest));
- if(cur_pos.x==dest.x && cur_pos.y==dest.y){
- // cost+=findDistance(cur_pos,dest);
- ans=min(ans,cost);
- return;
- }
- for(int i=0; i<n; i++){
- if(visited[i]==false){
- point temp,temp1;
- //stroring the cordinatess of womrhole start
- temp.x=worm[i].s1; temp.y=worm[i].s2;
- //storing the cordinates of ending of wormhole
- temp1.x=worm[i].d1; temp1.y=worm[i].d2;
- //distance of going from current position to the start of wormhole
- int cost1=findDistance(cur_pos,temp);
- //distance of going from current position to the end of wormhole
- int cost2=findDistance(cur_pos,temp1);
- visited[i]=true;
- //taking wormhole fromt its starting
- solve(temp1, cost + cost1 + worm[i].cost, n);
- //taking wormhole from its end
- solve(temp, cost + cost2 + worm[i].cost, n);
- //backtracking
- visited[i]=false;
- }
- }
- }
- int main() {
- int t;
- cin>>t;
- while(t--){
- cin>>n;
- cin>>src.x>>src.y>>dest.x>>dest.y;
- for(int i=0; i<n; i++){
- cin>>worm[i].s1>>worm[i].s2>>worm[i].d1>>worm[i].d2>>worm[i].cost;
- }
- for(int i=0; i<100; i++)
- visited[i]=false;
- ans=findDistance(src,dest);
- solve(src,0,n);
- cout<<ans<<endl;
- }
- return 0;
- }
- /*
- testcases:-
- 5
- 0
- 0 0 60 60
- 1
- 0 0 2 0
- 1 0 1 2 0
- 1
- 0 0 60 60
- 40 40 20 20 20
- 2
- 100 50 10 5
- 80 40 10 6 10
- 80 10 70 40 5
- 3
- 500 500 1000 1000
- 501 501 999 999 1000
- 1 1 499 499 100
- 1000 999 0 0 200
- output:-
- 120
- 2
- 100
- 41
- 305
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement