您的位置:首页 > 其它

hdu 2544 最短路 (邻接表)

2010-06-29 16:56 309 查看
]/*
¿´À´ÁÚ½Ó±íµÄЧÂʾÍÊDz»Ò»ÑùµÄ¡£¡£
*/
#include <iostream>
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

const int N = 105;
const int INF = 0x7f7f7f7f;
int dis
;
bool hash
;
struct node
{
int x;
int dis;
struct node *next;
};
node *map
, vex
;
void Init()
{
for(int i = 0; i < N; i++)
{
map[i] = &vex[i];
map[i]->next = NULL;
}
}
void creat(int x, int y, int dis)
{
node *p;
p = new node;
p->x = y;
p->dis = dis;
p->next = NULL;
map[x]->next = p;
map[x] = p;
}

struct Node
{
int x;
int dis;
friend bool operator < (Node a, Node b)
{
return a.dis > b.dis;
}
};
void BFS(int st, int n)
{
priority_queue<Node> Q;
Node P, M;
memset(hash, false, sizeof(hash));
memset(dis, 0x7f, sizeof(dis));
map[st] = &vex[st];
node *p;
p = map[st]->next;
for(; p != NULL; p = p->next)
{
M.dis = p->dis;
M.x = p->x;
dis[p->x] = p->dis;
Q.push(M);
}
hash[st] = true;
while(!Q.empty())
{
P = Q.top();
Q.pop();
hash[P.x] = true;
map[P.x] = &vex[P.x];
p = map[P.x]->next;
for(; p != NULL; p = p->next)
{
if(!hash[p->x] && P.dis + p->dis < dis[p->x])
{
dis[p->x] = P.dis + p->dis;
M.dis = dis[p->x];
M.x = p->x;
Q.push(M);
}
}
}

}
int main()
{
int n, m;
while(scanf("%d %d", &n, &m) && n + m)
{
Init();
while(m--)
{
int x, y, dis;
scanf("%d %d %d", &x, &y, &dis);
creat(x, y, dis);
creat(y, x, dis);
}
BFS(1, n);
printf("%d/n", dis
);
}
}


#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;

int cost[105][105];
int n;
int dis[105];
bool hash[105];
const int MAX = 0x7fffffff;

void Dijkstra()
{
 int i, j, k;
 memset(hash, false, sizeof(hash));
 hash[1] = true;
 for(i = 2; i <= n; i++)
 {
  int s = MAX;
  int t = 1;
  for(j = 2; j <= n; j++)
  {
   if(dis[j] < s && !hash[j])//这里忘记了hash
   {
    s = dis[j];
    t = j;
   }
  }
  for(k = 2; k <= n; k++)
  {
   if(!hash[k] && cost[t][k] != MAX && dis[k] > dis[t] + cost[t][k])
   {
    dis[k] = dis[t] + cost[t][k];
   }
  }
  hash[t] = true;
 }
 cout<<dis
<<endl;
}
int main()
{
 int i, j, m;
 while(scanf("%d %d", &n, &m) != EOF)
 {
  if(n == 0 && m == 0)
   continue;
  for(i = 0; i <= n; i++)
  for(j = 0; j <= n; j++)
  {
   if(i == j)
    cost[i][j] = 0;
   else
    cost[i][j] = MAX;
  }
  int a, b, t;
  for(i = 0; i < m; i++)
  {
   scanf("%d %d %d", &a, &b, &t);
   cost[a][b] = t;
   cost[b][a] = t;
  }
  for(i = 1; i <= n; i++)
  {
   dis[i] = cost[1][i];
  }
  Dijkstra();
 }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  struct null