暴力做法:(30pts)
把每条无向边拆成两条有向边.把每条边看成一个点,对于两条从一个点出去的边 建两条有向边 边权为较大值
这样是m^2的
优化:
可以用类似差分的思想来 然后出边之间做差分 对出边的边权排序 然后相邻边之间连边(小边向大边连权值为两边权值之差的边,大边向小边连权值为0的边)
这样入边只需向他的对应边连一个权值为原边权的边即可达到去最大值的效果。
#include<bits/stdc++.h> #define N 200005 #define ll long long #define INF 1000000000000000 using namespace std; template<class T> inline void read(T &x) { x=0; int f=1; static char ch=getchar(); while((!isdigit(ch))&&ch!='-') ch=getchar(); if(ch=='-') f=-1; while(isdigit(ch)) x=x*10+ch-'0',ch=getchar(); x*=f; } struct Edge { int to,next,val; }edge[2*N],road[8*N]; int n,m,tot=1,cnt=1,first[N],head[2*N],temp[N]; inline void addedge(int x,int y,int z) { tot++; edge[tot].to=y; edge[tot].next=first[x]; edge[tot].val=z; first[x]=tot; } inline void addroad(int x,int y,int z) { cnt++; road[cnt].to=y; road[cnt].next=head[x]; road[cnt].val=z; head[x]=cnt; } inline bool cmp(const int &a,const int &b) { return edge[a].val<edge[b].val; } int S,T; void Build() { S=1,T=2*(m+1); for(int i=1;i<=n;i++) { int top=0; for(int u=first[i];u;u=edge[u].next) temp[++top]=u; sort(temp+1,temp+top+1,cmp); for(int j=1;j<=top;j++) { int now=temp[j],next=temp[j+1]; if(edge[now].to==n) addroad(now,T,edge[now].val); if(i==1) addroad(S,now,edge[now].val); addroad(now^1,now,edge[now].val); //入边和出边 if(j<top) addroad(now,next,edge[next].val-edge[now].val),addroad(next,now,0); } } } ll dis[2*N]; typedef pair<ll,int> Pair; priority_queue<Pair,vector<Pair>,greater<Pair> > heap; bool vis[2*N]; void Dijkstra() { for(int i=2;i<=T;i++) dis[i]=INF; heap.push(make_pair(0,1)); while(!heap.empty()) { int now=heap.top().second; heap.pop(); if(vis[now]) continue; vis[now]=true; for(int u=head[now];u;u=road[u].next) { int v=road[u].to; if(dis[now]+road[u].val<dis[v]) { dis[v]=dis[now]+road[u].val; heap.push(make_pair(dis[v],v)); } } } } int main() { read(n),read(m); for(int i=1,x,y,z;i<=m;i++) read(x),read(y),read(z),addedge(x,y,z),addedge(y,x,z); Build(); Dijkstra(); cout<<dis[T]; return 0; }转载于:https://www.cnblogs.com/Patrickpwq/articles/9879497.html