#24226: 請問到底怎麼讀空白字串阿? 下面那樣會把輸入完n後的那個換行當第一個字串@@


angus.93321@gmail.com (bluemoon0321)

學校 : 國立科學工業園區實驗高級中學
編號 : 139711
來源 : [114.136.48.221]
最後登入時間 :
2021-08-21 11:35:29
b304. 00673 - Parentheses Balance -- UVa673 | From: [220.137.92.179] | 發表日期 : 2021-01-28 21:20

#include<iostream>

#include<stack>

#include<string>

using namespace std;

int main(){

int n;

cin>>n;

string a[n];

for(int i=0;i<n;i++){

getline(cin,a[i]);

}

int i=0;

while(i!=n){

bool legal=true;

stack<string> st;

int count=0;

int length=a[i].length();

for(int j=0;j<length;j++){

if(a[i][j]=='('){

st.push("(");

count++;

continue;

}

if(a[i][j]=='['){

st.push("[");

count++;

continue;

}

if(a[i][j]==')'){

if(st.empty()){

legal=false;

break;

}

if(st.top()!="("){

legal=false;

break;

}

else if(st.top()=="("){

st.pop();

continue;

}

}

if(a[i][j]==']'){

if(st.empty()){

legal=false;

break;

}

if(st.top()!="["){

legal=false;

break;

}

else if(st.top()=="["){

st.pop();

continue;

}

}

}

if(!st.empty()) cout<<"No"<<endl;

else if(count==0) cout<<"NO"<<endl;

else if(legal==true) cout<<"Yes"<<endl;

else cout<<"No"<<endl;

i++;

}

}

 
#24233: Re:請問到底怎麼讀空白字串阿? 下面那樣會把輸入完n後的那個換行當第一個字串@@


fire5386 (becaidorz)

學校 : 國立清華大學
編號 : 115822
來源 : [140.114.217.8]
最後登入時間 :
2024-04-13 22:06:23
b304. 00673 - Parentheses Balance -- UVa673 | From: [61.230.2.126] | 發表日期 : 2021-01-29 16:28

#include

#include

#include

using namespace std;

int main(){

int n;

cin>>n;

string a[n];

for(int i=0;i<n;i++){

getline(cin,a[i]);

}

int i=0;

while(i!=n){

bool legal=true;

stack st;

int count=0;

int length=a[i].length();

for(int j=0;j<length;j++){

if(a[i][j]=='('){

st.push("(");

count++;

continue;

}

if(a[i][j]=='['){

st.push("[");

count++;

continue;

}

if(a[i][j]==')'){

if(st.empty()){

legal=false;

break;

}

if(st.top()!="("){

legal=false;

break;

}

else if(st.top()=="("){

st.pop();

continue;

}

}

if(a[i][j]==']'){

if(st.empty()){

legal=false;

break;

}

if(st.top()!="["){

legal=false;

break;

}

else if(st.top()=="["){

st.pop();

continue;

}

}

}

if(!st.empty()) cout<<"No"<<endl;

else if(count==0) cout<<"NO"<<endl;

else if(legal==true) cout<<"Yes"<<endl;

else cout<<"No"<<endl;

i++;

}

}

第一行讀完數字後用cin.ignore()忽略換行的'\n'

接下來每行都直接讀整行,getline(cin, string)

以上

 
ZeroJudge Forum