【发布时间】:2020-07-15 02:15:40
【问题描述】:
- 给定的有向图有 N(1
例如:我们有 N=4 和 M=4 和 E={{1,4},{4,2},{1,2},{2,3}}, s=1 和 t= 3.所以答案是 1->2->3。
这是我的尝试:我使用 DFS 算法列出了从 s 到 t 的所有路径。并将它们添加到vector
中。然后,我对其进行排序并打印第一条路径。但我得到了 TLE。
现在,我不知道如何优化这个问题,你能帮我解决这个问题
这是我的代码
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define maxn (ll)(1e5+5)
#define pb push_back
vector<ll> adj[maxn];
vector<vector<ll>> poi;
vector<ll> really;
ll n,m,i,j,s,d,u,v;
void candy(vector<ll> yui){
poi.push_back(yui);
for(i=0;i<poi[0].size();i++) cout<<poi[0][i]+1<<" ";
exit(0);
}
void aka(ll u, ll d, bool visited[], ll path[], ll &path_index){
visited[u]=true;
path[path_index]=u;
path_index++;
if(u==d){
really.clear();
for(ll i=0;i<path_index;i++)
really.push_back(path[i]);
candy(really);
return ;
}
else{
sort(adj[u].begin(),adj[u].end());
for(ll i=0;i<adj[u].size();i++)
if(!visited[adj[u][i]]) aka(adj[u][i],d,visited,path,path_index);
}
path_index--;
visited[u]=false;
}
void solve(ll s, ll d){
bool visited[maxn];
ll path[maxn];
ll path_index = 0;
for(ll i=0;i<n;i++) visited[i]=false;
aka(s,d,visited,path,path_index);
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin>>n>>m>>s>>d;
s--;
d--;
while(m--){
cin>>u>>v;
u--;v--;
adj[u].pb(v);
}
solve(s,d);
}
【问题讨论】:
标签: c++ algorithm time-complexity complexity-theory graph-algorithm