POJ -- 2387 Til the Cows Come Home
2015-02-28 20:34
465 查看
代码实现:
SPFA:
Dijkatra:
SPFA:
#include<stdio.h> #include<string.h> #include<queue> using namespace std; int dis[1010],visit[1010],cnt[1010],top,n,t; struct Edge{ int num,val; Edge *next; Edge(int n=0,int v=0,Edge *p=0):num(n),val(v),next(p){} }*h[1010],e[4010]; void Addedge(int from,int to,int v){ Edge *p=&e[top++]; p->num=to; p->val=v; p->next=h[from]; h[from]=p; } queue<Edge>q; void SPFA(){ while(!q.empty()) q.pop(); for(int i=1;i<=n;i++) dis[i]=1e9; dis[1]=0; memset(visit,0,sizeof(visit)); memset(cnt,0,sizeof(cnt)); visit[1]=1; Edge head(1,0); Edge next; q.push(head); while(!q.empty()){ head=q.front(); q.pop(); visit[head.num]=0; //printf("*%d %d\n",head.num,head.val); for(Edge *p=h[head.num];p;p=p->next){ next=*p; if(dis[next.num]>dis[head.num]+next.val){ dis[next.num]=dis[head.num]+next.val; if(!visit[next.num]){ cnt[next.num]++; if(cnt[next.num]>=n) return; visit[next.num]=1; q.push(next); } } } } } int main(){ while(~scanf("%d%d",&t,&n)){ top=0; memset(h,0,sizeof(h)); int v1,v2,v; while(t--){ scanf("%d%d%d",&v1,&v2,&v); Addedge(v1,v2,v); Addedge(v2,v1,v); } SPFA(); printf("%d\n",dis ); } }
Dijkatra:
#include<stdio.h> #include<string.h> #include<queue> using namespace std; int dis[1010],visit[1010],cnt[1010],top,n,t; struct Edge{ int num,val; Edge *next; Edge(int n=0,int v=0,Edge *p=0):num(n),val(v),next(p){} bool operator<(const Edge& a)const{ return val>a.val; } }*h[1010],e[4010]; void Addedge(int from,int to,int v){ Edge *p=&e[top++]; p->num=to; p->val=v; p->next=h[from]; h[from]=p; } void Dijkstra(){ priority_queue<Edge> q; for(int i=1;i<=n;i++) dis[i]=1e9; dis[1]=0; memset(visit,0,sizeof(visit)); q.push(Edge(1,0)); while(!q.empty()){ int x=q.top().num; q.pop(); if(visit[x]==1) continue; visit[x]=1; if(x==n) break; for(Edge *p=h[x];p;p=p->next){ if(!visit[p->num]&&dis[p->num]>dis[x]+p->val){ dis[p->num]=dis[x]+p->val; q.push(Edge(p->num,dis[p->num])); } } } } int main(){ while(~scanf("%d%d",&t,&n)){ top=0; memset(h,0,sizeof(h)); int v1,v2,v; while(t--){ scanf("%d%d%d",&v1,&v2,&v); Addedge(v1,v2,v); Addedge(v2,v1,v); } Dijkstra(); printf("%d\n",dis ); } }
相关文章推荐
- POJ 2387 Til the Cows Come Home
- poj 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- poj_2387_Til the Cows Come Home
- 迪杰斯特拉 示例 : poj 2387 Til the Cows Come Home
- poj-2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- poj 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- 迪杰斯特拉 示例 : poj 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- poj 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- poj 2387 Til the Cows Come Home
- poj 2387 Til the Cows Come Home
- POJ 2387 Til the Cows Come Home
- poj 2387 Til the Cows Come Home
- Poj 2387 Til the Cows Come Home