您的位置:首页 > Web前端 > JavaScript

codeforces 20C 只能用dijstra堆优化或者spfa

2017-08-15 09:57 302 查看
inf这个数没开大!!!wa了17次!

一定要注意范围……………………555555555555555555555555555555


AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
using namespace std;
const int maxe=1e6+10;
const int maxv=1e5+10;
const long long inf=9e13;

int which=1;
int N,M;
int head[maxv];

struct EDGE
{
int d,w,next;
EDGE():next(-1){}
}e[maxe];

void add(int s,int d,int w)
{
e[which].d=d;
e[which].w=w;
e[which].next=head[s];
head[s]=which++;
}
void init()
{
memset(e,0,sizeof(e));
memset(head,-1,sizeof(head));
}

struct p
{
int pn,dist;
friend bool operator<(p a,p b)
{
return a.dist>b.dist;
}
};
long long dis[maxv];
int pre[maxv];
priority_queue<p> Q;
bool settled[maxv];

void dij(int st)
{
while(!Q.empty()) Q.pop();
memset(settled,0,sizeof(settled));
for(int i=1;i<=N;i++) dis[i]=inf;
dis[st]=0;

p stt;
stt.pn=st,stt.dist=0;
Q.push(stt);

while(!Q.empty())
{
p t=Q.top();
Q.pop();
//if(t.pn==N) return 1;

if(settled[t.pn]) continue;
settled[t.pn]=1;

for(int i=head[t.pn];i!=-1;i=e[i].next)
{
int to=e[i].d;
int mid=t.pn;
if(!settled[to]&&dis[to]>dis[mid]+e[i].w)
{
dis[to]=dis[mid]+e[i].w;
p tt;
tt.pn=to;
tt.dist=dis[to];
pre[tt.pn]=t.pn;
Q.push(tt);

}
}
}
//return 0;
}

void Find(int x)
{
if(x!=1) Find(pre[x]);

if(x!=1) printf(" ");
printf("%d",x);
}
int main()
{
//cout<<inf<<endl;
while(scanf("%d%d",&N,&M)==2)
{
which=1;
init();
memset(pre,0,sizeof(pre));
int t1,t2,t3;
for(int i=1;i<=M;i++)
{
scanf("%d%d%d",&t1,&t2,&t3);
add(t1,t2,t3);
add(t2,t1,t3);
}

dij(1);
if(dis
!=inf) Find(N);
else printf("-1");
printf("\n");
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐