1. 程式人生 > >hdu-1874 題解

hdu-1874 題解

empty ron als type bool style ext limit pop

裸SPFA模板題,註意算法中每次擴展完成後要把vis標記取消

#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<climits>
using namespace std;
struct edgetype
{
    int to;
    int len;
};
struct pointtype
{
    bool vis;
    vector<edgetype> next;
    int dis;
}point[
201]; queue<int> q; int main() { int n,m; while(cin>>n>>m) { for(int i=0;i<n;i++) { point[i].vis=false; point[i].dis=INT_MAX; point[i].next.clear(); } for(int i=1;i<=m;i++) { int
s,t,l; cin>>s>>t>>l; edgetype tmp; tmp.to=t; tmp.len=l; point[s].next.push_back(tmp); tmp.to=s; point[t].next.push_back(tmp); } int s,t; cin>>s>>t; point[s].dis
=0; point[s].vis=true; q.push(s); while(!q.empty()) { int now=q.front(); vector<edgetype>::iterator it; for(it=point[now].next.begin();it!=point[now].next.end();it++) { if(point[(*it).to].dis>point[now].dis+(*it).len) { point[(*it).to].dis=point[now].dis+(*it).len; if(!point[(*it).to].vis) { point[(*it).to].vis=true; q.push((*it).to); } } } point[now].vis=false; q.pop(); } int res=point[t].dis; if(res==INT_MAX) { res=-1; } cout<<res<<endl;; } return 0; }

hdu-1874 題解