題目描述:
有n個人,每個人都有各自的好友列表。給定一個閾值p,當A和B的共同好友數超過p則推薦A和B爲好友。請實現自動推薦直到沒有好友可以推薦(每次推薦默認同意,即一定成爲好友),然後進行一些查詢。
查詢1:A的好友數有幾個?如果A不在這n個裏面,輸出-1,否則輸出好友數;
查詢2:A和B是好友嗎?如果是則輸出0,否則輸出-1。
輸入:p n m x y
p爲閾值,n爲人數,m爲初始時的好友,x爲查詢1的個數,y爲查詢2的個數
注:
- 如果A是B的好友,B一定是A的好友;
- 每個人的人名用不超過20個字符的字符串表示,沒有重名的人;
- 人數不超過100.
2 3 3 3 3
A
B
C
A B
B C
A C
A
B
C
A B
C A
B C
應輸出:
2
2
2
0
0
0
這道題目主要考察的是圖,無向圖即可完成,考慮到數組表示法的方便性,用數組來實現無向圖。
#include <iostream>
#include <cstring>
#define MAX 100
#define name 20
using namespace std;
typedef struct{
int rs;//存放1表示二者是朋友
}gh[MAX][MAX];
typedef struct{
char n[MAX][name];//每個人的名字
int vexn; //人數
int arcm; //最開始的關係數,即m
gh gg;
}Graph;
int locate(Graph g,char *ch){//尋找某人在圖中的位置
for(int i=0;i<g.vexn;i++){
if(strcmp(g.n[i],ch)==0) return i;
}
return -1;
}
int main(){
int p,n,m,x,y;
Graph g;
cin>>p>>n>>m>>x>>y;
g.vexn=n,g.arcm=m;
for(int i=0;i<n;i++){
cin>>g.n[i];
}
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
g.gg[i][j].rs=0;
for(int i=0;i<m;i++){
int tp1,tp2;
char t1[name],t2[name];
cin>>t1>>t2;
tp1=locate(g,t1);
tp2=locate(g,t2);
if(tp1!=-1 && tp2!=-1){
g.gg[tp1][tp2].rs=g.gg[tp2][tp1].rs=1;
}
}
int count=1;
while(count!=0){//如果總體沒有朋友數增加,就停止
count=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
int f=0;
if(g.gg[i][j].rs!=1){
for(int k=0;k<n;k++){
if(g.gg[i][k].rs==1 && g.gg[j][k].rs==1)
f++;
}
if(f>=p){
count++;
g.gg[i][j].rs=g.gg[j][i].rs=1;
}
}
}
}
}
int *result1=new int[x];//存放問題1的結果
int *result2=new int[y];//存放問題2的結果
for(int i=0;i<x;i++){
int tmpnum=0;
char tmpx[name];
cin>>tmpx;
int lo=locate(g,tmpx);
if(lo!=-1){
for(int j=0;j<n;j++){
if(g.gg[lo][j].rs==1)
tmpnum++;
}
result1[i]=tmpnum;
}else{
result1[i]=-1;
}
}
for(int i=0;i<y;i++){
char ty1[name];
char ty2[name];
cin>>ty1>>ty2;
int t1=locate(g,ty1);
int t2=locate(g,ty2);
if(t1!=-1 && t2!=-1){
result2[i]=g.gg[t1][t2].rs;
}
}
for(int i=0;i<x;i++)
cout<<result1[i]<<endl;
for(int i=0;i<y;i++){
if(result2[i]==1){
cout<<0<<endl;
}else{
cout<<-1<<endl;
}
}
delete[] result1;
delete[] result2;
return 0;
}
如果有錯誤的地方,希望高手指正。