源于《2013年王道论坛计算机考研机试指南》与牛客网计算机考研复试上机题
1.预备知识
2.并查集
KY126 畅通工程
#include<iostream>
using namespace std;
int Tree[1001];
int findRoot(int x){
if(Tree[x]==-1)return x;
else{
int tmp=findRoot(Tree[x]);
Tree[x]=tmp;
return tmp;
}
}
int main(){
int n,m;
while(scanf("%d",&n)!=EOF){
if(n==0)break;
scanf("%d",&m);
for(int i=1;i<=n;i++)Tree[i]=-1;
for(int i=0;i<m;i++){
int a,b;
scanf("%d %d",&a,&b);
a=findRoot(a);
b=findRoot(b);
if(a!=b)Tree[a]=b;
}
int sum=0;
for(int i=1;i<=n;i++){
if(Tree[i]==-1)sum++;
}
printf("%d\n",sum-1);
}
return 0;
}
★More is better
#include<iostream>
using namespace std;
int Tree[1001],sum[1001];
int findRoot(int x){
if(Tree[x]==-1)return x;
else{
int tmp=findRoot(Tree[x]);
Tree[x]=tmp;
return tmp;
}
}
int main(){
int n,m;
while(scanf("%d",&n)!=EOF){
for(int i=1;i<=1001;i++){
Tree[i]=-1;
sum[i]=1;
}
for(int i=0;i<n;i++){
int a,b;
scanf("%d %d",&a,&b);
a=findRoot(a);
b=findRoot(b);
if(a!=b){
Tree[a]=b;
sum[b]+=sum[a];
}
}
int max=0;
for(int i=1;i<=1001;i++){
if(sum[i]>max)max=sum[i];
}
printf("%d\n",max);
}
return 0;
}
KY175 连通图
#include<iostream>
using namespace std;
int Tree[1001];
int findRoot(int x){
if(Tree[x]==-1)return x;
else{
int tmp=findRoot(Tree[x]);
Tree[x]=tmp;
return tmp;
}
}
int main(){
int n,m;
while(scanf("%d %d",&n,&m)!=EOF){
if(m==0&&n==0)break;
for(int i=1;i<=n;i++){
Tree[i]=-1;
}
for(int i=0;i<m;i++){
int a,b;
scanf("%d %d",&a,&b);
a=findRoot(a);
b=findRoot(b);
if(a!=b){
Tree[a]=b;
}
}
int flag=0;
for(int i=1;i<=n;i++){
if(Tree[i]==-1){
flag++;
}
}
if(flag==1)printf("YES\n");
else printf("NO\n");
}
return 0;
}
❓KY138 Head of a Gang
#include<iostream>
#include<algorithm>
#define MAXN 26*26*26+1
using namespace std;
int Tree[MAXN],sum[MAXN],number[MAXN];
int weight[MAXN],pos[1010],head[1010];
char s1[5],s2[5];
int findRoot(int x){
if(Tree[x]<0)return x;
else{
int tmp=findRoot(Tree[x]);
Tree[x]=tmp;
return tmp;
}
}
int char2int(char str[]){
int tmp=0;
for(int i=2;i>=0;i--){
tmp=26*tmp+str[i]-'A';
}
return tmp;
}
void print(int x){
int times=3;
while(times--){
printf("%c",x%26+'A');
x=(x-(x%26))/26;
}
printf(" ");
}
int main(){
int n,k;
while(scanf("%d %d",&n,&k)!=EOF){
int cur=0;
for(int i=0;i<MAXN;i++){
Tree[i]=-1;
weight[i]=0;
sum[i]=0;
number[i]=1;
}
for(int i=0;i<n;i++){
int a,b,num;
scanf("%s %s %d",&s1,&s2,&num);
a=char2int(s1);
b=char2int(s2);
pos[cur++]=a;
pos[cur++]=b;
a=findRoot(a);
b=findRoot(b);
weight[a]+=num;
weight[b]+=num;
if(a!=b){
Tree[a]+=Tree[b];
Tree[b]=a;
sum[a]=sum[a]+sum[b]+num;
number[a]+=1;
number[b]+=1;
}else{
sum[a]+=num;
}
}
int num=0;
for(int i=0;i<cur;i++){
if(Tree[pos[i]]<-2&&sum[pos[i]]>k){
int max=pos[i];
for(int j=0;j<cur;j++){
if(findRoot(pos[j])==pos[i]&&weight[pos[j]]>weight[pos[i]]){
max=pos[j];
}
}
head[num++]=max;
}
}
sort(head,head+num);
printf("%d\n",num);
for(int i=0;i<num;i++){
print(head[i]);
printf("%d\n",number[head[i]]);
}
}
return 0;
}
3.最小生成树MST
还是畅通工程