最短路径(巧妙的矩阵交换)
http://poj.org/problem?id=3268
题意:N头牛分别在N个农场有M条边的无向边,问所有牛中前往X农场,并返回走的最长距离的牛的距离。
解法:先求以X为源点到其他各农场的最短距离(相当于各牛返回),然后将M边反向,再以X为源点求到各农场的距离(相当于各牛去往X),统计每头牛走的距离,输出最大距离。
//#include<bits/stdc++.h> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <iostream> #include <string> #include <stdio.h> #include <queue> #include <stack> #include <map> #include <set> #include <string.h> #include <vector> #include <stdlib.h> using namespace std; typedef long long ll ; #define int ll #define mod 1000000007 #define gcd(m,n) __gcd(m, n) #define rep(i , j , n) for(int i = j ; i <= n ; i++) #define red(i , n , j) for(int i = n ; i >= j ; i--) #define ME(x , y) memset(x , y , sizeof(x)) int lcm(int a , int b){return a*b/gcd(a,b);} //ll quickpow(ll a , ll b){ll ans=1;while(b){if(b&1)ans=ans*a%mod;b>>=1,a=a*a%mod;}return ans;} //int euler1(int x){int ans=x;for(int i=2;i*i<=x;i++)if(x%i==0){ans-=ans/i;while(x%i==0)x/=i;}if(x>1)ans-=ans/x;return ans;} //const int N = 1e7+9; int vis[n],prime[n],phi[N];int euler2(int n){ME(vis,true);int len=1;rep(i,2,n){if(vis[i]){prime[len++]=i,phi[i]=i-1;}for(int j=1;j<len&&prime[j]*i<=n;j++){vis[i*prime[j]]=0;if(i%prime[j]==0){phi[i*prime[j]]=phi[i]*prime[j];break;}else{phi[i*prime[j]]=phi[i]*phi[prime[j]];}}}return len} #define INF 0x3f3f3f3f #define PI acos(-1) #define pii pair<int,int> #define fi first #define se second #define lson l,mid,root<<1 #define rson mid+1,r,root<<1|1 #define pb push_back #define mp make_pair #define all(v) v.begin(),v.end() #define size(v) (int)(v.size()) #define cin(x) scanf("%lld" , &x); const int N = 1e7+9; const int maxn = 1e5+9; const double esp = 1e-6; int head[maxn] , tol ; int n , m , x ; struct node{ int to , w; bool operator < (const node x) const{ return w > x.w ; } node(int a , int b){to = a , w = b;} node(){} }; struct Graph{ int to , w , next; }g[maxn<<1]; void add(int u , int v , int w){ g[++tol] = {v , w , head[u]}; head[u] = tol; } int vis[maxn] , dis[maxn] ,ans[maxn]; void dijia(int r){ ME(vis , 0); rep(i , 1 , n)dis[i] = INF; dis[r] = 0 ; priority_queue<node>q; q.push(node(r , dis[r])); node now; while(!q.empty()){ now = q.top();q.pop(); if(vis[now.to]) continue; for(int i = head[now.to] ; i ; i = g[i].next){ int v = g[i].to; if(dis[v] > dis[now.to] + g[i].w){ dis[v] = dis[now.to] + g[i].w; q.push(node(v , dis[v])); } } } } void init(){ tol = 0 ; ME(head , 0); } int u[maxn] , v[maxn], w[maxn]; void solve(){ scanf("%lld%lld%lld" , &n , &m , &x); rep(i , 1 , m){ scanf("%lld%lld%lld" , &u[i] , &v[i] , &w[i]); add(u[i] , v[i] , w[i]); } dijia(x); rep(i , 1 , n) ans[i] += dis[i]; init(); rep(i , 1 , m){ add(v[i] , u[i] , w[i]); } dijia(x); rep(i , 1 , n) ans[i] += dis[i]; int ma = -INF; rep(i , 1 , n) ma = max(ma , ans[i]); cout << ma << endl; } signed main() { //int t; //scanf("%lld" , &t); //while(t--) solve(); }