3424:Candies
Candies POJ - 3159
Dijkstra代码(WA 10次):
vector内是又申请好的空间的,但queue和stack一半是存储的地址
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <sstream>
#include <algorithm>
#define ll long long
#define mes(x,y) memset(x,y,sizeof(x))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
const ll INFF = 2000000;
const ll maxn = 99999999;
ll n, m, k, i, j, vb;
struct node {
ll end, value;
};
bool operator <(const node & n1,const node & n2) {
return n1.value > n2.value;
}
priority_queue<node>pq;
bool flag[300040] = { 0 };
vector<vector<node>>v;
int main() {
FAST_IO;
while (cin >> n >> m) {
node n1;
mes(flag, 0);
v.clear();
v.resize(n + 1);
ll x, y, z;
for (i = 1; i <= m; i++) {
cin >> x >> y >> z;
n1.end = y;
n1.value = z;
v[x].push_back(n1);
}
n1.end = 1;
n1.value = 0;
pq.push(n1);
while (!pq.empty()) {
n1 = pq.top(); pq.pop();
if (flag[n1.end])continue;
flag[n1.end] = true;
if (n1.end == n) {
cout << n1.value << endl;
break;
}
for (i = 0, j = v[n1.end].size(); i < j; i++) {
node n2; n2.end = v[n1.end][i].end;
if (flag[n2.end])continue;
n2.value = v[n1.end][i].value + n1.value;
pq.push(n2);
}
}
}
}
Spfa代码:
唯一注意的一点:别用queue队列,队列会TLE,用stack
#include<iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <functional>
#include <ctime>
#include <iomanip>
#include <numeric>
#include <sstream>
#include <algorithm>
#define ll int
#define PI acos(-1)
#define mes(x,y) memset(x,y,sizeof(x))
#define lp pair<ll, ll>
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;
inline int read() {
int x = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-')
f = -1;
ch = getchar();
}
while (ch >= '0' && ch <= '9') {
x = (x << 1) + (x << 3) + (ch ^ 48);
ch = getchar();
}
return x * f;
}
const ll inf = 10000000000000005;
ll n, m, i, j, k = 0, t, w, flag, x, y, z, sum;
string s1, s2, s;
struct node {
ll end, len, next;
}v[151000];
ll dis[151000], ismove[151000], head[151000];
void addnode(ll x, ll y, ll z, ll flag) {
v[flag].end = y;
v[flag].len = z;
v[flag].next = head[x];
head[x] = flag;
}
void Spfa(ll f) {
mes(dis, inf); mes(ismove, 0);
dis[f] = 0; stack<ll>que; que.push(f);
while (!que.empty()) {
t = que.top(); que.pop(); ismove[t] = 0;
for (ll i = head[t]; i > 0; i = v[i].next) {
w = v[i].end;
if (dis[w] > dis[t] + v[i].len) {
dis[w] = dis[t] + v[i].len;
if (ismove[w] == 0)que.push(w);
ismove[w] = 1;
}
}
}
}
int main() {
n = read(); m = read();
for (i = 1, mes(head, 0); i <= m; i++) {
x = read(); y = read(); z = read();
addnode(x, y, z, i);
}Spfa(1);
cout << dis[n] << endl;
return 0;
}