UVa 1148 - The mysterious X network
/*
Accepted
Algorithm: BFS
Solution: (Total cost to reach the destination) - 1
*/
#include<bits/stdc++.h>
using namespace std;
#define sf scanf
#define pf printf
#define psb push_back
#define fast ios_base::sync_with_stdio(false)
typedef map<string, int>mpsi;
typedef map<int, string>mpis;
typedef long long LL;
const int high = 2e5+10;
vector<int>adj[high];
int visited[high], cost[high];
void CLR()
{
for(int i=0; i<high; i++)
{
adj[i].clear();
cost[i] = 0;
visited[i] = 0;
}
}
void BFS(int s , int d)
{
visited[s] = 1;
cost[s] = 0;
queue<int>Q;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
if(u == d) return;
int sze = adj[u].size();
for(int i=0; i<sze; i++)
{
int v = adj[u][i];
if(!visited[v])
{
visited[v] = 1;
Q.push(v);
cost[v] = cost[u] + 1;
}
}
}
}
int main()
{
fast;
int i , j , nc, u , v , test, tc=0;
cin >> test;
while(test--)
{
CLR();
if(tc) cout << "\n";
tc = 1;
int N;
cin >> N;
for(i=0; i<N; i++)
{
cin >> u >> nc;
for(j=0; j<nc; j++)
{
cin >> v;
adj[u].psb(v);
adj[v].psb(u);
}
}
int start , endd;
cin >> start >> endd;
BFS(start, endd);
cout << start << " " << endd << " " << cost[endd]-1 << "\n";
}
return 0;
}
Accepted
Algorithm: BFS
Solution: (Total cost to reach the destination) - 1
*/
#include<bits/stdc++.h>
using namespace std;
#define sf scanf
#define pf printf
#define psb push_back
#define fast ios_base::sync_with_stdio(false)
typedef map<string, int>mpsi;
typedef map<int, string>mpis;
typedef long long LL;
const int high = 2e5+10;
vector<int>adj[high];
int visited[high], cost[high];
void CLR()
{
for(int i=0; i<high; i++)
{
adj[i].clear();
cost[i] = 0;
visited[i] = 0;
}
}
void BFS(int s , int d)
{
visited[s] = 1;
cost[s] = 0;
queue<int>Q;
Q.push(s);
while(!Q.empty())
{
int u = Q.front();
Q.pop();
if(u == d) return;
int sze = adj[u].size();
for(int i=0; i<sze; i++)
{
int v = adj[u][i];
if(!visited[v])
{
visited[v] = 1;
Q.push(v);
cost[v] = cost[u] + 1;
}
}
}
}
int main()
{
fast;
int i , j , nc, u , v , test, tc=0;
cin >> test;
while(test--)
{
CLR();
if(tc) cout << "\n";
tc = 1;
int N;
cin >> N;
for(i=0; i<N; i++)
{
cin >> u >> nc;
for(j=0; j<nc; j++)
{
cin >> v;
adj[u].psb(v);
adj[v].psb(u);
}
}
int start , endd;
cin >> start >> endd;
BFS(start, endd);
cout << start << " " << endd << " " << cost[endd]-1 << "\n";
}
return 0;
}
Comments
Post a Comment