算法:
链接到问题:- https://www.spoj.com/status/ns=25150439
#include <bits/stdc++.h>
using namespace std;
#define int long long int
const int INF = 0x3f3f3f3f;
int32_t main()
{
int t;
cin>>t;
while(t--)
{
int n, r, m;
cin>>n>>r>>m;
vector< vector<int> > adj(n+1, vector<int> (n+1, 0));//adjacency Matrix
for(int i=0;i<r;i++)
{
int x, y;
cin>>x>>y;
adj[x][y] = 1;
adj[y][x] = 1;
}
vector<int> protect(n+1, 0); // protect[i] :- number of protectors of city i
vector<int> assigned(n+1, -1);// assigned[i] :- strength of soldier assigned to city i, if not assigned then -1.
for(int i=0;i<m;i++)
{
int x, y;
cin>>x>>y;
assigned[x] = y;
protect[x] = 1;
}
int exflag = 0; // flag to exit when protectors of city become > 1
for(int s=1;s<n+1;s++)
{
if(assigned[s] != -1) // if city is assigned a soldier, then carry bfs
{
queue<int> q;
vector<int> visited(n+1, 0);
vector<int> distance(n+1, INF);
q.push(s);
visited[s] = 1;
distance[s] = 0;
while(!q.empty())
{
int u = q.front();
q.pop();
for(int i=1;i<n+1;i++)
{
if(adj[u][i] == 1 && visited[i] == 0)
{
distance[i] = distance[u] + 1;
if(distance[i] <= assigned[s])
{
q.push(i);
visited[i] = 1;
protect[i]++;
}
if(protect[i] == 2)
{
cout<<"No"<<endl;
exflag = 1;
break;
}
}
}
if(exflag)
{
break;
}
}
if(exflag)
{
break;
}
}
}
if(!exflag)
{
int flag = 0; // to check if some city is unprotected
for(int i=1;i<n+1;i++)
{
if(protect[i] == 0)
{
flag = 1;
cout<<"No"<<endl;
break;
}
}
if(!flag) cout<<"Yes"<<endl;
}
}
return 0;
}