BFS
点的数量,边的数量,以及边的连接情况(邻接矩阵),用黑白两种颜色给点染色,要求相连的两个点不能同颜色,如果能成功染色,输出被染成白色的点
#include<stdio.h> #define SIZE 100 int map[SIZE][SIZE]; int queue[SIZE * SIZE]; int color[SIZE]; int visit[SIZE]; int ncases; int n,m; int ans; int head = 0; int rear = 0; int tab; void bfs(int step) { queue[rear] = step; rear++; color[step]=1; visit[step]=1; while(head < rear) { int temp = queue[head]; head++; for(int i=1;i<=n;i++) { tab=0; if(map[temp][i] == 1) { if(color[i] == 0) { color[i] -= color[temp]; queue[rear]=i; rear++; visit[i]=1; } else if(color[i] == color[temp]) { tab=1; ans=-1; break; } } } if(tab) break; } } int main(){ freopen("input.txt","r",stdin); scanf("%d",&ncases); for(int i=0;i<ncases;i++) { scanf("%d%d",&n,&m); ans=0; int x,y; for(int i=1;i<=m;i++) { scanf("%d%d",&x,&y); map[x][y]=1; map[y][x]=1; } for(int i=1;i<=n;i++) { if(visit[i] == 0) bfs(i); if(tab) break; } if(ans==0) { for(int i=1;i<=n;i++) { if(color[i] == -1) ans++; } printf("%d\n",ans); for(int i=1;i<=n;i++) { if(color[i] == -1) printf("%d ",i); } printf("\n"); } else printf("%d\n",ans); } }
/*测试用例 9 5 5 1 2 2 3 3 4 4 5 5 1 6 6 1 2 2 3 3 4 4 5 5 6 6 1 4 5 1 2 2 3 3 4 4 1 4 2 4 6 1 2 2 3 3 4 4 1 4 2 1 3 4 4 1 2 2 3 3 4 4 1 5 6 1 2 1 4 2 3 2 5 3 4 5 4 12 13 1 2 1 4 2 3 3 4 4 5 5 6 6 7 7 8 8 5 5 9 4 10 9 10 11 12 5 4 1 4 1 3 3 5 2 5 7 5 1 4 1 3 3 5 2 5 6 7 测试结果 -1 3 2 4 6 -1 -1 2 2 4 2 2 4 6 2 4 6 8 9 12 3 2 3 4 4 2 3 4 7 */
时间: 2024-10-22 06:08:53