I applied BFS
algorithm is like this -
for each soldier I ran BFS from his source city and whichever city it protects I fill the source city as value in array cities. Initially all values are -1 , if a soldier protects the city say 'i', then cities[i] = source city of that soldier.
condition for No-
- if a city is protected by two soldiers
- if a city is left unprotected at the end
code is -
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(0);
int main()
{
int t,n,r,m,u,v,src,capacity;
bool dec_capacity, invalid_flag;
cin>>t;
while(t--)
{
invalid_flag = 0; // value = 1 -> NO , value = 0 -> YES
cin>>n>>r>>m;
ll cities[n+1];
memset(cities, -1 , sizeof(cities));
vector<ll> graph[n+1];
for(ll i=0;i<r;i++)
{
cin>>u>>v;
graph[u].push_back(v);
graph[v].push_back(u);
}
vector< pair<ll,ll> > soldiers;
for(ll i=0;i<m;i++)
{
cin>>u>>v;
soldiers.push_back(make_pair(u,v));
}
queue<ll> q;
for(ll i=0;i<m;i++)
{
src = soldiers[i].first; // src city of soldier
capacity = soldiers[i].second;
if(cities[src]>0) // check if home city is already protected by another soldier
{
invalid_flag =1;
break;
}
cities[src] = src;
q.push(src);
while(!q.empty())
{
u = q.front();
q.pop();
dec_capacity =0;
if(capacity>0)
{
for(ll j=0; j<graph[u].size();j++)
{
v = graph[u][j];
if(cities[v]>0 && cities[v]!=src) // if city is already protected by another soldier
{
invalid_flag = 1;
break;
}
if(cities[v]==-1)
{
dec_capacity =1;
q.push(v);
cities[v]=src;
}
}
}
if(invalid_flag)
break;
if(dec_capacity)
capacity--;
}
if(invalid_flag)
break;
}
// check if any city is left unprotected
for(ll i=1;i<=n;i++)
{
if(cities[i]==-1)
{
invalid_flag=1;
break;
}
}
if(invalid_flag)
cout<<"NO\n";
else
cout<<"YES\n";
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire