Path of greater than equal to k length
Given a graph, a source vertex in the graph and a number k, find if there is a simple path, of path length greater then or equal to k,(without any cycle) starting from a given source and ending at any other vertex.
Source vertex should always be 0.
Input : Source s = 0, k = 58
Output : True
There exists a simple path 0 -> 7 -> 1
-> 2 -> 8 -> 6 -> 5 -> 3 -> 4
Which has a total distance of 60 km which
is more than 58.
Input : Source s = 0, k = 62
Output : False
In the above graph, the longest simple
path has distance 61 (0 -> 7 -> 1-> 2
-> 3 -> 4 -> 5-> 6 -> 8, so output
should be false for any input greater
than 61.
#include<bits/stdc++.h>
using namespace std;
bool dfs(vector<pair<int,int>> vp[],int v,int k,bool vis[]){
vis[v]=true;
if(k<=0)
return true;
for(int i=0;i<vp[v].size();i++){
if(!vis[vp[v][i].first]){
vis[vp[v][i].first]=true;
//cout << v << " " << vp[v][i].first << endl;
return dfs(vp,vp[v][i].first,k-vp[v][i].second,vis);
}
}
return false;
}
int main(){
int t;
cin >> t;
while(t--){
int v,e,k;
cin >> v >> e >> k;
vector<pair<int,int>> vp[v];
int s,d,dist;
for(int i=0;i<e;i++){
cin >> s >> d >> dist;
vp[s].push_back(make_pair(d,dist));
vp[d].push_back(make_pair(s,dist));
}
bool vis[v]={false};
int flag=0;
for(int i=0;i<vp[0].size();i++){
for(int j=0;j<v;j++)
vis[j]=false;
vis[0]=true;
if(dfs(vp,vp[0][i].first,k-vp[0][i].second,vis)){
cout << "1\n";
flag=1;
break;
}
}
if(flag==0)
cout << "0\n";
}
return 0;
}