-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlc520.cpp
107 lines (88 loc) · 1.99 KB
/
lc520.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct UndirectedGraphNode
{
int label;
vector<UndirectedGraphNode* > neighbor;
UndirectedGraphNode(int val) :label(val) {}
};
class soluton
{
public:
soluton();
~soluton();
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node)
{
if (node=NULL)
{
return NULL;
}
map<UndirectedGraphNode*, UndirectedGraphNode*> cloneMap;
//establish index search
queue<UndirectedGraphNode*> q;
q.push(node);
//clone the root
UndirectedGraphNode* cloneNode = new UndirectedGraphNode(node->label);
cloneMap[node] = cloneNode;
while (!q.empty())
{
UndirectedGraphNode* temp=q.front();
q.pop();
for (size_t i = 0; i < temp->neighbor.size(); i++)
{
UndirectedGraphNode* adj = temp->neighbor[i];
if (cloneMap.find(adj)==cloneMap.end())
{
UndirectedGraphNode * newnode = new UndirectedGraphNode(adj->label);
cloneMap[temp]->neighbor.push_back(newnode);
cloneMap[adj] = newnode;
q.push(adj);
}
else
{
cloneMap[temp]->neighbor.push_back(cloneMap[adj]);
}
}
}
return cloneNode;
}
private:
};
soluton::soluton()
{
}
soluton::~soluton()
{
}
class Solution {
public:
int canCompleteCircuit(vector<int> &gas, vector<int> &cost) {
int current = 0;
int start = gas.size(); //start from the end to beginning. gas.size and 0 is the same position
int total = 0;
do
{
if (total+gas[current]-cost[current]>=0)
{
++current;
total += gas[current] - cost[current];
}
else
{
--start;
total += (gas[start] - cost[start]);
}
} while (current!=start);
do {
if (total + gas[current] - cost[current] >= 0) {
total += (gas[current] - cost[current]);
current++; // can go from current to current+1
}
else {
start--; //not enough gas, try to start the one before origin start point.
total += (gas[start] - cost[start]); // ie 4->5 cost +gas4
}
} while (current != start);
return total >= 0 ? start % gas.size() : -1;
}
};