dijkstra - 堆优化
先看两种对vector 的赋值方法
1 .
int t, n;
struct node{
int to, cost;
};
vector<node>edge[1005];
int main() {
int a, b, c;
while(~scanf("%d%d", &t, &n)){
for(int i = 1; i <= t; i++){
scanf("%d%d%d", &a, &b, &c);
node v;
v.to = b, v.cost = c;
edge[a].push_back(v);
v.to = a, v.cost = c;
edge[b].push_back(v);
}
for(int i = 1; i <= 5; i++){
for(int j = 0; j < edge[i].size(); j++){
node v = edge[i][j];
printf("%d %d\n", v.to, v.cost);
}
printf("@@@@@@@@@@@@@@\n");
}
printf("***\n");
}
return 0;
}
2 .
int t, n;
struct node{
int to, cost;
node(int x, int y){
to = x;
cost = y;
}
};
vector<node>edge[1005];
int main() {
int a, b, c;
while(~scanf("%d%d", &t, &n)){
for(int i = 1; i <= t; i++){
scanf("%d%d%d", &a, &b, &c);
edge[a].push_back(node(b, c));
edge[b].push_back(node(a, c));
}
for(int i = 1; i <= 5; i++){
for(int j = 0; j < edge[i].size(); j++){
node v = edge[i][j];
printf("%d %d\n", v.to, v.cost);
}
printf("@@@@@@@@@@@@@@\n");
}
printf("***\n");
}
return 0;
}
板子 :
const int inf = 1<<29;
int t, n;
struct node
{
int to, cost;
node(int a = 0, int b = 0):to(a), cost(b){}
};
struct pp
{
friend bool operator< (pp n1, pp n2){
return n1.c > n2.c;
}
int v, c; // 当前点的位置,点上的值
pp(int _v = 0, int _c = 0):v(_v), c(_c){}
};
vector<node>edge[1005];
int d[1005];
bool vis[1005];
void dij(){
priority_queue<pp>que;
memset(vis, false, sizeof(vis));
for(int i = 1; i <= n; i++) d[i] = inf;
d[1] = 0;
while(!que.empty()) que.pop();
que.push(pp(1, d[1]));
while(!que.empty()){
pp temp = que.top();
que.pop();
int u = temp.v;
if (vis[u]) continue;
vis[u] =1 ;
for(int i = 0; i < edge[u].size(); i++){
int to_ = edge[u][i].to;
int co = edge[u][i].cost;
if (!vis[to_] && d[u] + co < d[to_]){
d[to_] = d[u] + co;
que.push(pp(to_, d[to_]));
}
}
}
}
int main() {
int a, b, c;
while(~scanf("%d%d", &t, &n)){
for(int i = 1; i <= 1000; i++){
edge[i].clear();
}
for(int i = 1; i <= t; i++){
scanf("%d%d%d", &a, &b, &c);
edge[a].push_back(node(b, c));
edge[b].push_back(node(a, c));
}
dij();
printf("%d\n", d[n]);
}
return 0;
}
东北日出西边雨 道是无情却有情

浙公网安备 33010602011771号