#include<iostream>
using namespace std;
#define M 100000
int qux[1000000], quy[1000000];
int n, m, f, r;
int **a, visit[100005];
int temp[100005][2];
int gt[100005], mau[100005];
int number[100005], dem[100005];
int ketqua;
void Init()
{
f = r = 0;
for(int i = 1; i <= n; i++)
visit[i] = 0;
}
int BFS()
{
Init();
qux[r] = 1;
//quy[r] = 1;
r++;
visit[1] = 1;
int temp;
while(f != r)
{
temp = qux[f];
f++;
for(int i = 1; i<= number[temp]; i++)
{
int next = a[temp][i];
if( visit[next] == 0)
{
visit[next] = 1;
mau[next] = 1 - mau[temp];
if(mau[next] != gt[next]){
ketqua++;
}
qux[r++] = next;
}else{
if(mau[next] == mau[temp]){
return -1;
}
}
}
}
return ketqua;
}
int main()
{
int T;
freopen("input.txt","r", stdin);
//freopen("output.txt","w", stdout);
cin>>T;
for(int tc=1;tc<=T;tc++){
ketqua = 0;
cin >>n >> m;
for(int i = 1; i <= n; i++){
number[i] = 0;
mau[i] = -1;
}
char buff;
for(int i= 1; i <= n; i++){
cin >> buff;
if(buff == 'B'){
gt[i] = 1;
}else{
gt[i] = 0;
}
}
int x, y;
a = new int*[n+1];
for(int i = 0; i < m; i++)
{
cin >> x >> y;
//cout<<x<<":"<<y<<endl;
number[x]++;
number[y]++;
temp[i][0] = x;
temp[i][1] = y;
}
for(int i=1;i<=n;i++){
a[i] = new int[number[i]];
dem[i] = 0;
}
for(int i = 0; i < m; i++)
{
x = temp[i][0];
y = temp[i][1];
dem[x]++;
dem[y]++;
a[x][dem[x]] = y;
a[y][dem[y]] = x;
}
//BFS///
mau[1] = gt[1];
int result1 = BFS();
int result2 = n - result1;
if(result1>result2){
cout<<result2<<endl;
}else{
cout<<result1<<endl;
}
}
}
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.