36th Chengdu semi-finals Network Competition hdoj4039 The Social Network (graph creation + string processing), 36thhdoj4039
This is a Chinese online competition in Chengdu one year.
This idea is very simple, but from the time point of consideration, it is best not to use matrix storage, I use the chain forward star.
Online query is used. Map is used for string numbers, because it is convenient. The friend to be recommended is actually a friend of a friend (this refers to a friend who is directly connected by a side in the figure ).
Therefore, you only need to search for friends and count them.
Note: there cannot be spaces in the output.
Code:
#include<iostream>using namespace std;#include<cstdio>#include<cstdlib>#include<cstring>#include<map>#include<algorithm>int n,m;char s11[20],s22[20];string g[20100],l[20100];int next[201000],head[2010],key[201000];int num;void add(int u,int v){ key[num]=v; next[num]=head[u]; head[u]=num++;}int main(){ int T,pp=0; scanf("%d",&T); while (T--) { map<string,int> hash; int n,m,i,j,k; string s1,s2; int cnt=0; num=0; scanf("%d%d",&n,&m); memset(head,-1,sizeof(head)); for (i=0;i<n;++i) { scanf("%s%s",s11,s22); s1=string(s11); s2=string(s22); if (hash[s1]==0) hash[s1]=++cnt,l[cnt]=s1; if (hash[s2]==0) hash[s2]=++cnt,l[cnt]=s2; add(hash[s1],hash[s2]); add(hash[s2],hash[s1]); } printf("Case %d:\n",++pp); for (i=0;i<m;++i) { scanf("%s",s11); s1=string(s11); int p=hash[s1]; int f[20100],flag[20010]; memset(f,0,sizeof(f)); memset(flag,0,sizeof(flag)); for (k=head[p];k!=-1;k=next[k]) flag[key[k]]=-1; for (k=head[p];k!=-1;k=next[k]) if (key[k]!=p) { for (j=head[key[k]];j!=-1;j=next[j]) if (key[j]!=key[k] && key[j]!=p && flag[key[j]]==0) { f[key[j]]++; } } int Max=-1; for (k=1;k<=cnt;++k) { Max=max(Max,f[k]); // printf("%d\n",f[k]); } if (Max==0) { printf("-\n"); continue; } int q=0; for (k=1;k<=cnt;++k) if (Max==f[k]) { g[q++]=l[k]; } sort(g,g+q); for (k=0;k<q-1;++k) cout << g[k] << " "; cout << g[q-1]; cout << endl; } } return 0;}