Wednesday, April 20, 2011

336 - A Node Too Far


#include <iostream>
#include <cstring>
#include<cstdio>
#include <queue>
#define M 35
using namespace std;

struct Node
{
int id,ttl;
};
bool List[M][M];
int nodeID[M],cntNode,NC;

int GetIndex(int id);
void ReadInput();
int BFS(int start,int ttl);

int main()
{
int s,t,i,k=1;
//freopen("in.txt","r",stdin);
while ( scanf("%d",&NC)&& NC)
{
ReadInput();
while(scanf("%d%d",&s,&t)&&s)
{
i = GetIndex(s);
printf("Case %d: %d nodes not reachable from node %d with TTL = %d.\n",k++,BFS(i,t),s,t);
}
}
return 0;
}

int GetIndex(int id)
{
for (int i=0;i<cntNode;i++)
if (nodeID[i] == id)
return i;
    return -1;
}

void ReadInput()
{
cntNode = 0;
memset( List,0,sizeof(List) );
int x,y,xid,yid;
for ( int i=0;i<NC;i++)
{
scanf("%d%d",&x,&y);
xid = GetIndex(x);
if (xid<0)
xid=cntNode,nodeID[cntNode++]=x;

yid=GetIndex(y);
if (yid<0)
yid=cntNode,nodeID[cntNode++]=y;

List[xid][yid]=List[yid][xid]=true;
}
}

int BFS(int s,int t)
{
bool visited[M]={false};
Node node,tmp;int i;

queue<Node>Q;node.id=s;
node.ttl=0;Q.push(node);

while (!Q.empty())
{
node=Q.front();Q.pop();

if (node.ttl>t||visited[node.id])continue;
visited[node.id]=true;
for(i=0;i<cntNode;i++)
if (List[node.id][i]&&node.ttl<t&& !visited[i])
{
tmp.id=i;
tmp.ttl=node.ttl+1;
Q.push(tmp);
}
}
int res=0;
for (i=0;i<cntNode;i++)
if (!visited[i])res++;
    return res;
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.