#include<cstdio>
#include<cstring>
#include<iostream>
#include<vector>
#include<map>
#define SZ 1005
using namespace std;
map<string,int>mymap;
vector<int>graph[SZ],graph1[SZ];
bool color[SZ];
int topsort[SZ],k;
char str[30],str1[30],str2[30];
string s,s1,s2;
void DFS(int p)
{
color[p]=1;
for(int j=0;j<graph[p].size();j++)
{
int u=graph[p][j];
if(color[u]==0)
{
DFS(u);
}
}
topsort[k++] = p;
}
void DFS1(int p)
{
color[p]=1;
for(int l=0;l<graph1[p].size();l++)
{
int u=graph1[p][l];
if(color[u]==0)
{
DFS1(u);
}
}
}
int main()
{
int P,T,a,b,c,counter,i;
while(scanf("%d %d",&P,&T)==2)
{
if(P==0 && T==0)
{
break;
}
getchar();
for(i=1;i<=P;i++)
{
gets(str);
s=str;
mymap[s]=i;
}
for(i=1;i<=T;i++)
{
gets(str1);
gets(str2);
s1=str1;
s2=str2;
a=mymap[s1];
b=mymap[s2];
graph[a].push_back(b);
graph1[b].push_back(a);
}
k=0;
for(i=1;i<=P;i++)
{
if(!color[i])
{
DFS(i);
}
}
memset(color,0,sizeof(color));
counter=0;
for(i=k-1;i>=0;i--)
{
c=topsort[i];
if(color[c]==0)
{
counter++;
DFS1(c);
}
}
printf("%d\n",counter);
for(i=0;i<=P;i++)
{
graph[i].clear();
graph1[i].clear();
}
memset(color,0,sizeof(color));
memset(topsort,0,sizeof(topsort));
mymap.clear();
}
return 0;
}
#include<cstring>
#include<iostream>
#include<vector>
#include<map>
#define SZ 1005
using namespace std;
map<string,int>mymap;
vector<int>graph[SZ],graph1[SZ];
bool color[SZ];
int topsort[SZ],k;
char str[30],str1[30],str2[30];
string s,s1,s2;
void DFS(int p)
{
color[p]=1;
for(int j=0;j<graph[p].size();j++)
{
int u=graph[p][j];
if(color[u]==0)
{
DFS(u);
}
}
topsort[k++] = p;
}
void DFS1(int p)
{
color[p]=1;
for(int l=0;l<graph1[p].size();l++)
{
int u=graph1[p][l];
if(color[u]==0)
{
DFS1(u);
}
}
}
int main()
{
int P,T,a,b,c,counter,i;
while(scanf("%d %d",&P,&T)==2)
{
if(P==0 && T==0)
{
break;
}
getchar();
for(i=1;i<=P;i++)
{
gets(str);
s=str;
mymap[s]=i;
}
for(i=1;i<=T;i++)
{
gets(str1);
gets(str2);
s1=str1;
s2=str2;
a=mymap[s1];
b=mymap[s2];
graph[a].push_back(b);
graph1[b].push_back(a);
}
k=0;
for(i=1;i<=P;i++)
{
if(!color[i])
{
DFS(i);
}
}
memset(color,0,sizeof(color));
counter=0;
for(i=k-1;i>=0;i--)
{
c=topsort[i];
if(color[c]==0)
{
counter++;
DFS1(c);
}
}
printf("%d\n",counter);
for(i=0;i<=P;i++)
{
graph[i].clear();
graph1[i].clear();
}
memset(color,0,sizeof(color));
memset(topsort,0,sizeof(topsort));
mymap.clear();
}
return 0;
}
0 comments: (+add yours?)
Post a Comment