您的位置:首页 > 其它

HDU-4725 The Shortest Path in Nya Graph

2017-12-13 21:59 537 查看
题目链接:https://vjudge.net/problem/HDU-4725

自己懒得写了,就拷些别人的过来

n个点,m条边,以及相邻层之间移动的代价c,给出每个点所在的层数,以及m条边,每条边有u,v,c,表示从节点u到v(无向),并且移动的代价 c ,问说从 1 到 n 的代价最小是多少。

将层抽象出来成为n个点(对应编号依次为n+1 ~ n+n),然后层与层建边,点与点建边,层与在该层上的点建边 (边长为0),点与相邻层建边 (边长为c)。

我这个代码刚开始是TLE,我硬做了些优化,可以AC了,还是会TLE(看脸),懒得再改了。。。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
using namespace std;
const int N=2*1e5+10;
struct edge
{
int to;
int c;
int next;
};
struct belong
{
int p;
int next;
};
int id
,head
,num;
edge e[N*20];
int d
;
bool vis
;
int n,m,c;
int main()
{
int T,kase=0;
scanf("%d",&T);
while(T--)
{
int u,v,w;
scanf("%d%d%d",&n,&m,&c);
memset(head,-1,sizeof(head));
num=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&id[i]);
e[num].to=n+id[i];
e[num].c=0;
e[num].next=head[i];
head[i]=num;
num++;
v=id[i]-1;
if(v>=1&&v<=n)
{
e[num].to=i;
e[num].c=c;
e[num].next=head[n+v];
head[n+v]=num;
num++;
}
v=id[i]+1;
if(v>=1&&v<=n)
{
e[num].to=i;
e[num].c=c;
e[num].next=head[n+v];
head[n+v]=num;
num++;
}
}
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
e[num].to=v;
e[num].c=w;
e[num].next=head[u];
head[u]=num;
num++;
e[num].to=u;
e[num].c=w;
e[num].next=head[v];
head[v]=num;
num++;
}
memset(d,-1,sizeof(d));
memset(vis,false,sizeof(vis));
queue<int> q;
q.push(1);
vis[1]=true;d[1]=0;
while(!q.empty())
{
u=q.front();
q.pop();vis[u]=false;
for(int i=head[u];i!=-1;i=e[i].next)
{
v=e[i].to;
if(d[v]==-1||d[v]>d[u]+e[i].c)
{
d[v]=d[u]+e[i].c;
if(!vis[v])
{
q.push(v);
vis[v]=true;
}
}
}
}
printf("Case #%d: %d\n",++kase,d
);
}
return 0;
}




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: