5
Hint The graph given in sample input is a complete graph, that each pair of vertex has an edge connecting them, so there's only 1 connected block at first. The first 3 lines of output are 1s because after deleting the first 3 edges of the graph, all vertexes still connected together. But after deleting the first 4 edges of the graph, vertex 1 will be disconnected with other vertex, and it became an independent connected block. Continue deleting edges the disconnected blocks increased and finally it will became the number of vertex, so the last output should always be N.
题解:
这道题是说给你一些点和边,这些点是按照所给的方式连接的
现在让你按照连接好的图,在按照这个顺序将边删除,观看每进行一次删除,模块数是多少?
通俗的讲就是有多少个集合?
如果按照正向思维当删除一个边时,模块数不一定会增加,因为还有其他的点连接着
现在按照逆向思维,倒着进行,刚开始是独立的N个模块,(并查集)每进行一次边的连接判断是不是在同一个集合
如果不在同一个集合,连接后,模块数减一,否则模块数不变。
代码:
///HDU 4496 D-city ///并查集的逆向思维 #include <iostream> #include <algorithm> #include <cstdio> #include <cstring> #include <string> using namespace std; const int maxx=10005; int par[maxx]; int coun[100005]; struct rod { int u,v; }s[100005];///M取值在100000; ///寻找根结点 int find(int x) { if(par[x]!=x) return par[x]=find(par[x]); return par[x]; } ///集合合并 int unite(int x,int y) { x=find(x); y=find(y); if(x!=y) { par[x]=y; return 1; } return 0; } int n,m; int main() { while(~scanf("%d %d",&n,&m)) { for(int i=0;i<n;i++) par[i]=i; int ans=n; ///逆向输入 for(int i=m-1;i>=0;i--) { scanf("%d %d",&s[i].u,&s[i].v); } for(int i=0;i<m;i++) { coun[m-i-1]=ans;///存放的是模块数 if(unite(s[i].u,s[i].v)) { ans--; ///如果两者之间可以建立边则模块减一 } } for(int i=0;i<m;i++) { printf("%d\n",coun[i]); } } return 0; }
代码2:
#include <iostream> #include <cstdio> #include <cstring> #define M 100000+10 #define N 10000+10 using namespace std; int n,m; struct node { int u,v; } s[M]; int B[N],ans[M]; int fine(int x) { if(B[x]!=x) B[x]=fine(B[x]); return B[x]; } int main() { int i; while(~scanf("%d%d",&n,&m)) { memset(ans,0,sizeof(ans)); memset(s,0,sizeof(s)); for(i=0;i<n;i++) B[i]=i; for(i=0; i<m; i++) { scanf("%d%d",&s[i].u,&s[i].v); } int sum=n; for(i=m-1;i>=0;i--) { ans[i]=sum; int xx=fine(s[i].u); int yy=fine(s[i].v); if(xx!=yy) { sum--; B[xx]=yy; } } for(i=0;i<m;i++) printf("%d\n",ans[i]); } return 0; }