제출 #1318243

#제출 시각아이디문제언어결과실행 시간메모리
1318243vtnooGrowing Vegetable is Fun 3 (JOI19_ho_t3)C++20
0 / 100
1097 ms58260 KiB
#include <bits/stdc++.h>
#define L(i, j, k) for(int i = (j); i <= (k); i++)
#define R(i, j, k) for(int i = (j); i >= (k); i--)
#define ll long long
#define sz(a) ((int) a.size())
#define all(a) a.begin(), a.end()
#define vi vector<ll>
#define pb emplace_back
#define me(a, x) memset(a, x, sizeof(a))
#define fst first
#define snd second
#define ii pair<int, int>
using namespace std;
int n;
bool valid(string s){
	for(int i=1;i<n;i++){
		if(s[i]==s[i-1])return false;
	}
	return true;
}
int main(){
	ios::sync_with_stdio(false); 
	cin.tie(nullptr);
	cin>>n;
	string s;cin>>s;
	if(valid(s)){cout<<0<<endl;return 0;}
	queue<string>q;
	q.push(s);
	int ans=1e9;
	unordered_map<string,int>d,v;
	d[s]=0;
	v[s]=1;
	while(sz(q)){
		string u=q.front();q.pop();
		if(d[u]==n*n)continue;
		for(int i=1;i<n;i++){
			string c=u;
			swap(c[i],c[i-1]);
			if(v.count(c))continue;
			d[c]=d[u]+1;
			if(valid(c)){
				ans=min(ans,d[c]);
			}
			v[c]=1;
			q.push(c);
		}
	}
	if(ans==1e9)cout<<-1<<endl;
	else cout<<ans<<endl;
}	
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...