当前位置: 代码迷 >> 综合 >> PTA | 1013 Battle Over Cities
  详细解决方案

PTA | 1013 Battle Over Cities

热度:63   发布时间:2024-01-27 04:31:09.0

并查集实现,并查集写的不熟,时间复杂度也比想要的高,但过啦!开心!
AC代码:

#include <iostream>
#include <vector>using namespace std;struct highway{int u,v;
};
int pre[1010];
vector<highway> h;int unionSearch(int root){int son,tmp;son=root;while(root != pre[root])root=pre[root];while(son != root){tmp=pre[son];pre[son]=root;son=tmp;}return root;
}int join(int root1, int root2,int c){int x,y;x=unionSearch(root1);y=unionSearch(root2);if(x!=y){pre[x]=y;c--;}return c;
}int main(){int n,m,k;scanf("%d %d %d",&n,&m,&k);for(int i=0;i<m;i++){highway temp;scanf("%d %d",&temp.u,&temp.v);h.push_back(temp);}for(int i=0;i<k;i++){for(int j=1;j<=n;j++) pre[j]=j;int city;int count=n;scanf("%d",&city);for(int j=0;j<m;j++){if(h[j].u!=city&&h[j].v!=city){count=join(h[j].u,h[j].v,count);}}printf("%d\n",count-2);}system("pause");return 0;
}