UVALive - 6885 Flowery Trails 最短路

题目链接:

http://acm.hust.edu.cn/vjudge/problem/129723

Flowery Trails

Time Limit: 3000MS

题意

求所有位于最短路上的边的权值和的两倍。

题解

起点跑一遍单源最短路,得到距离数组d[],终点跑一遍最短路,得到d2[]。枚举每条边,如果d[u]+d2[v]+wd[n-1]||d[v]+d2[u]+wd[n-1],那么ans+=w;

代码

#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define X first
#define Y second
#define mkp make_pair
#define lson (o<<1)
#define rson ((o<<1)|1)
#define mid (l+(r-l)/2)
#define sz() size()
#define pb(v) push_back(v)
#define all(o) (o).begin(),(o).end()
#define clr(a,v) memset(a,v,sizeof(a))
#define bug(a) ;//cout<<#a<<" = "<<a<<endl
#define rep(i,a,b) for(int i=a;i<(b);i++)

typedef long long LL;
typedef vector<int> VI;
typedef pair<int,int> PII;
typedef vector<pair<int,int> > VPII;

const int INF=0x3f3f3f3f;
const LL INFL=0x3f3f3f3f3f3f3f3fLL;
const double eps=1e-8;

//start----------------------------------------------------------------------

const int maxn=10000+10;

struct Edge{
	int u,v,d;
	Edge(int u,int v,int d):u(u),v(v),d(d){}
}; 

struct HeapNode{
	int d,u;
	HeapNode(int d,int u):d(d),u(u){}
	bool operator < (const HeapNode&tmp) const {
		return d>tmp.d;
	}
};

struct Dijkstra{
	int n,m;
	vector<Edge> egs;
	vector<int> G[maxn];
	bool done[maxn];
	int d[maxn],d2[maxn];
	vector<int> p[maxn];
	
	void init(int n){
		this->n=n;
		for(int i=0;i<=n;i++) G[i].clear(),p[i].clear();
		egs.clear();
	}
	
	void addEdge(int u,int v,int d){
		egs.push_back(Edge(u,v,d));
		m=egs.size();
		G[u].push_back(m-1);
	}
	
	void dijkstra(int *d,int s){
		priority_queue<HeapNode> Q;
		rep(i,0,n) d[i]=INF;
		d[s]=0;
		clr(done,0);
		Q.push(HeapNode(0,s));
		while(!Q.empty()){
			HeapNode x=Q.top(); Q.pop();
			int u=x.u;
			if(done[u]) continue;
			done[u]=1;
			rep(i,0,G[u].size()){
				Edge& e=egs[G[u][i]];
				if(d[e.v]>d[u]+e.d){
					d[e.v]=d[u]+e.d;
					Q.push(HeapNode(d[e.v],e.v));
				}
			}
		}
	}
	
	void solve(){
		dijkstra(d,0);
		dijkstra(d2,n-1);
		LL ans=0;
		rep(i,0,m){
			Edge& e=egs[i];
			if(d[e.u]+d2[e.v]+e.d==d[n-1]||d[e.v]+d2[e.u]+e.d==d[n-1]){
				ans+=e.d;
			} 
		}
		printf("%lld\n",ans);
	}
}dij;

int n,m;

int main() {
	while(scanf("%d%d",&n,&m)==2){
		dij.init(n);
		rep(i,0,m){
			int u,v,w;
			scanf("%d%d%d",&u,&v,&w);
			dij.addEdge(u,v,w);
			dij.addEdge(v,u,w);
		}
		dij.solve();
	} 
    return 0;
}

//end-----------------------------------------------------------------------

Notes

起点跑一次,终点跑一次,然后枚举边来判断最短路上的边的方法不错。

posted @ 2016-08-15 22:27  fenicnn  阅读(147)  评论(0编辑  收藏  举报