参考博客:https://blog.youkuaiyun.com/vermouth_x/article/details/79855456
D - Detour Gym - 101666D
题目大意:
给定n个点,m条边,起点为0,终点为1。对于路径上除终点外的每一个点,其到终点1的最短路径上都有一个标志,问是否能在绕开标志的情况下找到一条从0到1的路径,存在的话打印路径。
思路:
大致思路是将有标志的边删掉,然后dfs看0到1是否连通。
问题的重点在于如何快速优雅地找到有标志的边。
从题意中可以看到,所有的标志都是到1的最短路上的标志,所以可以把1做为源点,跑最短路。dfs的时候判断一下边的两个端点u和v是否满足dist[u]=dist[v]+weight[u][v],若满足,则该边不通
get迪杰斯特拉 nlogn算法,阅读理解题,注意理解。另外:迪杰斯特拉算法不能求最长路径,我坑了~
#include <iostream>
#include <cstdio>
#include<cstdlib>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include<time.h>
#include <stack>
#include <list>
#include <set>
#include <sstream>
#include <iterator>
using namespace std;
#define FOPI freopen("input.in", "r", stdin)
#define DOPI freopen("output.out", "w", stdout)
#define ll long long int
#define fro(i,a,n) for(ll i=a;i<n;i++)
#define pre(i,a,n) for(ll i=n-1;i>=a;i--)
#define mem(a,b) memset(a,b,sizeof(a))
#define ls l,mid,rt<<1
#define rs mid+1,r,rt<<1|1
#define fi first
#define se second
#define s_d(a) scanf("%d",&a)
#define s_lld(a) scanf("%lld",&a)
#define s_s(a) scanf("%s",a)
#define s_ch(a) scanf("%c",&a)
typedef pair<ll,ll> P;
ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);}
const double PI = 3.1415926535897932;
const double EPS=1e-6;
const int INF=0x3f3f3f3f;
const int maxn = 2e5+100;
int lowbit(int x){return x&(-x);}
struct edge
{
int to;
int value;
edge(){}
edge(int a,int b):to(a),value(b){}
bool operator<(edge a) const
{
return value>a.value;
}
};
vector<edge> s[maxn];
int dis[maxn];
int m,n;
int book[maxn];
int path[maxn];
bool flag=0;
int sum=1;
void dijsktra(int x)
{
mem(dis,INF);
priority_queue<edge,vector<edge> > ss;
dis[x]=0;
ss.push(edge(x,0));
while(!ss.empty())
{
edge a;
a=ss.top();
ss.pop();
book[a.to]=1;
fro(i,0,s[a.to].size())
{
int b=s[a.to][i].to;
if(!book[b]&&dis[b]>dis[a.to]+s[a.to][i].value)
{
dis[b]=dis[a.to]+s[a.to][i].value;
ss.push(edge(b,dis[b]));
}
}
}
}
void dfs(int a)
{
//cout<<"!!!"<<endl;
if(a==1)
{
flag=1;
return ;
}
fro(i,0,s[a].size())
{
edge b=s[a][i];
//cout<<a<<" "<<b.to<<endl;
if(dis[a]==dis[b.to]+s[a][i].value)
{
//cout<<dis[b.to]<<" "<<dis[a]<<" "<<s[a][i].value<<endl;
continue;
}
if(!book[b.to])
{
//sum+=s[a][b.to].value;
sum++;
book[b.to]=1;
path[a]=b.to;
dfs(b.to);
}
if(flag)
return;
}
}
int main()
{
ios::sync_with_stdio(0);
cin>>m>>n;
fro(i,0,n)
{
int a,b,c;
cin>>a>>b>>c;
s[a].push_back(edge(b,c));
s[b].push_back(edge(a,c));
}
dijsktra(1);//反向dijsktra
mem(path,-1);
mem(book,0);
book[0]=1;
dfs(0);
if(flag)
{
vector<int> ans;
ans.push_back(0);
int a=0;
while(path[a]!=1)
{
//cout<<"???"<<endl;
ans.push_back(path[a]);
a=path[a];
}
ans.push_back(1);
cout<<ans.size();
fro(i,0,ans.size())
{
cout<<" "<<ans[i];
}
}
else
cout<<"impossible"<<endl;
return 0;
}
/*
4 5
0 2 5
2 1 5
0 3 10
3 1 20
3 2 5
4 3
0 1 10
1 2 20
2 3 30
7 9
0 1 800
6 2 300
2 3 75
3 4 80
4 5 50
4 1 100
1 6 35
0 2 120
0 3 100
*/