题目大意:在计算机网络中,每条信息都有一个TTL值,在信息到达一个节点时,TTL值首先减1,如果TTL为0,则丢弃该信息报文。给一个网络的配置,给定源点和TTL值,判断该网络中有多少节点不可到达。
无权图(无向)上的单源最短路问题,可用BFS解决。
#include <cstdio>
#include <iostream>
#include <cstring>
#include <map>
#include <queue>
using namespace std;
#define NODEN 35 map<int, int> vertex; void new_vertex(int x)
{
if (!vertex.count(x))
{
int t = vertex.size() + ;
vertex[x] = t;
}
} int main()
{
#ifdef LOCAL
freopen("in", "r", stdin);
#endif
int n, kase = ;
while (scanf("%d", &n) && n)
{
int x, y;
vertex.clear();
vector<int> G[NODEN];
for (int i = ; i < n; i++)
{
scanf("%d%d", &x, &y);
new_vertex(x);
new_vertex(y);
G[vertex[x]].push_back(vertex[y]);
G[vertex[y]].push_back(vertex[x]);
}
int s, ttl, cnt;
int dist[NODEN];
while (scanf("%d%d", &s, &ttl) && (s || ttl))
{
int st = vertex[s];
queue<int> q;
memset(dist, -, sizeof(dist));
dist[st] = ;
q.push(st);
cnt = ;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int i = ; i < G[u].size(); i++)
{
int v = G[u][i];
if (dist[v] != -) continue;
dist[v] = dist[u] + ;
if (dist[v] > ttl) goto s;
q.push(v);
cnt++;
}
}
s: int ans = vertex.size() - cnt;
printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n", ++kase, ans, s, ttl);
}
}
return ;
}