Pink and Blue Final Answer

 avatar
ptrdung
c_cpp
25 days ago
2.6 kB
1
Indexable
Never
#include<iostream>
using namespace std;
#define pii pair<int,int>
#define piii pair<pii,int>
const int mn =1e5+6;
const int maxS = 2e6+6;

template <typename T>
class Vector{
private:
	int size;
	int capacity;
	T *array;
	void expand(int newCapacity)
	{ 
	    if (newCapacity <= size)
	        return;
	
	    T * old = array; 
	    array = new T[newCapacity];
	    
	    for (int i = 0; i < size; i++)
	        array[i] = old[i];
	    
		delete[] old;
	    capacity = newCapacity;
	}
public:
	Vector(int initCapacity = 1)
	{
	    size = 0;
	    capacity = initCapacity;
	    array = new T[capacity];
	}
	~Vector() 
	{
	    delete[] array;
	}
	Vector & operator=(Vector & rhs) 
	{
	    if (this != &rhs)
		{
	        delete[] array;
	        size = rhs.size;
	        capacity = rhs.capacity;
	        array = new T[capacity];
	        for (int i = 0; i < size; i++)
	            array[i] = rhs.array[i];
	    }
	    
	    return *this;
	}
	int Size() 
	{
	    return size;
	}
	T & operator[](int index) 
	{
	    return array[index];
	}
	void push_back(T newElement) 
	{
	    if (size == capacity)
	        expand(2 * size);
	    array[size] = newElement;
	    size++;
	}
	void popBack() 
	{
	    size--;
	}
	void clear() 
	{
	    size = 0;
	}
};
Vector<int> g[mn];
char a[mn];
int no[mn],dx[mn],dy[mn],xet[mn];
int n,m,dem1,dem2,res,check;
void dfs(int x)
{
	for(int i=0;i<g[x].Size();i++)
	{
		int y=g[x][i];
		if(xet[y]==xet[x]){check=1;break;}
		if(xet[y]!=0)continue;
		if(check==0)
		{
			xet[y]=3-xet[x];
			if(xet[y]==1&&a[y]=='G')dem1++;
			if(xet[y]==2&&a[y]=='B')dem1++;
			if(xet[y]==1&&a[y]=='B')dem2++;
			if(xet[y]==2&&a[y]=='G')dem2++;
			dfs(y);
		}
	}
}
int main()
{
	ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
	//freopen("1.txt","r",stdin);
	//freopen(".out","w",stdout);
	int te=10;
	cin>>te;
	for(int tes=1;tes<=te;tes++)
	{
		//cout<<"Case "<<tes<<"\n";
		res=0;
		check=0;
		cin>>n>>m;
		for(int i=1;i<=n;i++){
			cin>>a[i];
			g[i].clear();
			xet[i]=0;
		}
		for(int i=1;i<=m;i++)
		{
			int x,y;
			cin>>x>>y;
			g[x].push_back(y);
			g[y].push_back(x);
		}
		for(int i=1;i<=n;i++)
			if(xet[i]==0)
				{
					dem1=dem2=0;
					xet[i]=1;
					if(xet[i]==1&&a[i]=='G')dem1++;
					if(xet[i]==2&&a[i]=='B')dem1++;
					if(xet[i]==1&&a[i]=='B')dem2++;
					if(xet[i]==2&&a[i]=='G')dem2++;
					dfs(i);
					if(dem1<dem2)res+=dem1;
					else res+=dem2;
			}
			//for(int i=1;i<=n;i++)cout<<xet[i]<<" ";
		if(check)cout<<-1<<'\n';
		else cout<<res<<'\n';
	}
	return 0;
}
Leave a Comment