Problem Statement : 10507 - Waking up brain
Source : UVA Online Judge
Category : Graph Theory
Algorithm : bfs
Verdict : Accepted
- #include<bits/stdc++.h>
- using namespace std;
- #define vi vector<int>
- #define mx 30
- #define em emplace_back
- vi graph[mx];
- int on[mx];
- int dist[mx];
- int tnode,tedge;
- char str[4];
- set<int>used[mx];
- int toint(char ch){
- return ch-'A'+1;
- }
- void init(){
- for(int i=0;i<mx;i++){
- graph[i].clear();
- on[i]=0;
- used[i].clear();
- }
- }
- int bfs(int x,int y,int z){
- on[x]=on[y]=on[z]=1;
- queue<int>q;
- q.emplace(x);
- q.emplace(y);
- q.emplace(z);
- dist[x]=dist[y]=dist[z]=0;
- int mxdist=0;
- int visit=3;
- while(!q.empty()){
- int u=q.front();
- q.pop();
- for(int v:graph[u]){
- if(on[v])continue;
-
- used[v].emplace(u);
-
- if(used[v].size()==3){
- dist[v]=dist[u]+1;
- if(dist[v]>mxdist)mxdist=dist[v];
- on[v]=1;
- visit++;
- q.emplace(v);
- }
- }
- }
- if(visit<tnode) return -1;
- return mxdist;
- }
- int main(){
-
-
- while(cin>>tnode>>tedge){
- init();
- cin>>str;
- int x=toint(str[0]);
- int y=toint(str[1]);
- int z=toint(str[2]);
- cin.ignore();
- for(int i=1;i<=tedge;i++){
- cin>>str;
- int u=toint(str[0]);
- int v=toint(str[1]);
- graph[u].em(v);
- graph[v].em(u);
- }
- int year=bfs(x,y,z);
-
- if(year==-1)cout<<"THIS BRAIN NEVER WAKES UP"<<endl;
- else cout<<"WAKE UP IN, "<<year<<", YEARS"<<endl;
- }
-
- return 0;
- }
No comments:
Post a Comment