#include<stdio.h>
#include<string>
#include<map>
#include<iostream>
using namespace std;
char tab[2100][2100];
map<string,int> name_map;
int main() {
int n,m;
while(scanf("%d%d",&n,&m)!=EOF) {
if(n==0 && m==0) return 0;
int _n=0,x,y;
string name1,name2;
name_map.clear();
while(_n<n) {
cin>>name1;
name_map.insert(make_pair(name1,_n++));
}
while(m--) {
cin>>name1>>name2;
x=name_map.find(name1)->second;
y=name_map.find(name2)->second;
for(_n=0;_n<n;++_n) {
if(tab[x][_n] && _n!=y) tab[y][_n]=1;
if(tab[y][_n] && _n!=x) tab[x][_n]=1;
}
tab[x][y]=tab[y][x]=1;
}
int cnt=0;
for(x=0;x<n;++x) {
for(y=0;y<n;++y) {
if(tab[x][y]) {
cnt++;
tab[x][y]=0;
}
}
}
if(cnt==n*n-n) printf("YES\n");
else printf("NO\n");
}
return 0;
}
map[i] will return the value in map for string i. My solution was a lot similar to this. Not posting it.
ReplyDeleteOne optimization
In loop
tab[x][_n]=tab[y][_n]=tab[x][_n]||tab[y][_n];
and finally
check tab[i][j] or tab[j][i] !=1 for i<j for No
Got it. Even better if you post your solution.
ReplyDelete