20分代码:
#include<bits/stdc++.h>
using namespace std;
int f[1001],d[1001];
int find(int x)
{
if(f[x]==x) return x;
f[x]=find(f[x]);
return f[x];
}
int main()
{
memset(d,0,sizeof(d));
char opt;
int n,m,p,q,x,y;
cin>>n>>m;
for(int i=1;i<=n;i++) f[i]=i;
for(int i=1;i<=m;i++)
{
scanf("%c",&opt);
if(opt!='E'&&opt!='F') scanf("%c",&opt);
scanf("%d%d",&p,&q);
if(opt=='F')
{
x=find(p),y=find(q);
if(x!=y) f[x]=y;
}
if(opt=='E')
{
if(d[p]==0) d[p]=q;
if(d[q]==0) d[q]=p;
x=find(p),y=find(d[q]);
if(x!=y) f[x]=y;
x=find(q),y=find(d[p]);
if(x!=y) f[x]=y;
}
}
for(int i=1;i<=n;i++) f[i]=find(i);
sort(f+1,f+n+1);
int ans=unique(f+1,f+n+1)-(f+1);
cout<<ans;
return 0;
}
AC代码:
#include<bits/stdc++.h>
using namespace std;
int f[1001],d[1001];
int find(int x)
{
if(f[x]==x) return x;
f[x]=find(f[x]);
return f[x];
}
int main()
{
memset(d,0,sizeof(d));
char opt;
int n,m,p,q,x,y;
cin>>n>>m;
for(int i=1;i<=n;i++) f[i]=i;
for(int i=1;i<=m;i++)
{
scanf("%c",&opt);
while(opt!='E'&&opt!='F') scanf("%c",&opt);
scanf("%d%d",&p,&q);
if(opt=='F')
{
x=find(p),y=find(q);
if(x!=y) f[x]=y;
}
if(opt=='E')
{
if(d[p]==0) d[p]=q;
if(d[q]==0) d[q]=p;
x=find(p),y=find(d[q]);
if(x!=y) f[x]=y;
x=find(q),y=find(d[p]);
if(x!=y) f[x]=y;
}
}
for(int i=1;i<=n;i++) f[i]=find(i);
sort(f+1,f+n+1);
int ans=unique(f+1,f+n+1)-(f+1);
cout<<ans;
return 0;
}
为什么把if换成while就AC了,按理说行与行之间不就只有一个回车吗?