您的位置:首页 > 其它

hdu 1874畅通工程续一秒(最短路)

2017-12-18 15:08 274 查看
题意:给一个无向图,边权为正值,求s,t间最短路,可能s,t间没有路,此时输出-1

          注意这个图可能有重边,查询时可能有s=t的情况

          使用半个spfa做的这题(没用判负圈),用一个并查集判断st是否有路。因为存的是邻接表,多重边都会被算进去,不需要加特殊操作,点都初始化了也直接解决了s=t的问题。

#include <bits/stdc++.h>
using namespace std;

int v,e,s,t;
vector< pair<int,int> > ve[300];

int vis[300],fa[300],d[300];
const int maxn=20000;
void init()
{
memset(ve,0,sizeof(ve));

memset(vis,0,sizeof(vis));
memset(fa,0,sizeof(fa));

for(int i=1;i<=v;i++)
{
d[i]=maxn;
fa[i]=i;
}

int cs,ce,cw;
for(int i=1;i<=e;i++)
{
cin>>cs>>ce>>cw;
ve[cs+1].push_back( make_pair(ce+1,cw) );
ve[ce+1].push_back( make_pair(cs+1,cw) );

}
cin>>s>>t;
s++;
t++;
d[s]=0;
}
int froot(int v)
{
if(fa[v]==v)return v;
else return froot(fa[v]);
}
void spfa()
{
queue<int> q;
q.push(s);
vis[s]=1;

while(!q.empty())
{
int u=q.front();
q.pop();
vis[u]=0;
for(int i=0;i<ve[u].size();i++)
{
int cv=ve[u][i].first,cw=ve[u][i].second;
if(cw+d[u]<d[cv])
{
d[cv]=cw+d[u];
fa[cv]=u;
if(vis[cv]==0)
{
vis[cv]=1;

q.push(cv);

}
}
}

}

}

int main()
{
while(cin>>v>>e)
{

init();
spfa();

if(froot(t)!=s)cout<<"-1"<<endl;
else cout<<d[t]<<endl;

}

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