//If instead of strings we were given with numbers this would have been just a simple topological sorting.
//But we are given strings so instead of int we use string and instead of array we need to use maps .
//To check for duplicates we need to use set .
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
typedef vector<string> vs;
map<string,vs> m;
map<string,int> indeg;
set<string> exist;
queue<string> q;
int ans=0;
int main(){
char s[10000];
bool found=1;
string current;
set<string> se;
while(scanf("%s",s)!=EOF){
if(found){
current=s;
found=0;
se.clear();
exist.insert(current);
}
else if(s[0]=='0'){
found=1;
}
else{
string ss=s;
if(se.find(ss)==se.end()){
indeg[current]++;
se.insert(ss);
m[ss].pb(current);
}
}
}
set<string>::iterator it;
for(it=exist.begin();it!=exist.end();it++){
string cur = *it;
if(indeg[cur]==0){
ans++;
q.push(cur);
}
}
while(!q.empty()){
string temp=q.front();
q.pop();
int x=m[temp].size();
for(int i=0;i<x;i++){
string next=m[temp][i];
indeg[next]--;
if(indeg[next]==0){
q.push(next);
ans++;
}
}
}
printf("%d",ans);
}
//But we are given strings so instead of int we use string and instead of array we need to use maps .
//To check for duplicates we need to use set .
#include<bits/stdc++.h>
using namespace std;
#define pb push_back
typedef vector<string> vs;
map<string,vs> m;
map<string,int> indeg;
set<string> exist;
queue<string> q;
int ans=0;
int main(){
char s[10000];
bool found=1;
string current;
set<string> se;
while(scanf("%s",s)!=EOF){
if(found){
current=s;
found=0;
se.clear();
exist.insert(current);
}
else if(s[0]=='0'){
found=1;
}
else{
string ss=s;
if(se.find(ss)==se.end()){
indeg[current]++;
se.insert(ss);
m[ss].pb(current);
}
}
}
set<string>::iterator it;
for(it=exist.begin();it!=exist.end();it++){
string cur = *it;
if(indeg[cur]==0){
ans++;
q.push(cur);
}
}
while(!q.empty()){
string temp=q.front();
q.pop();
int x=m[temp].size();
for(int i=0;i<x;i++){
string next=m[temp][i];
indeg[next]--;
if(indeg[next]==0){
q.push(next);
ans++;
}
}
}
printf("%d",ans);
}
No comments:
Post a Comment