Topic link: http://codeforces.com/contest/1153/problem/C
Main idea of the title: It is required that there should be no correct expression in the prefix, but the whole string is the correct expression. Construct parentheses and put them first (, verify the conformity after construction). This is my first cf game, because cf is too late. This problem was not worked out at that time, and later it was supplemented with a feeling of greed.
Specific ideas in the code
ac Code:
import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.Scanner; //Construct parentheses and place them first.( //The prefix is required to contain no correct expression, but the entire string is the correct expression. public class Main { public static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); String a=sc.next(); char ctr[]=a.toCharArray(); if(n%2!=0||ctr[0]==')'||ctr[n-1]=='('){//It is impossible to match odd numbers. The beginning and end must be'(')', respectively. System.out.println(":("); return; } int l=0,r=0; for(int i=0;i<n;i++){ if(ctr[i]=='(') //Number of existing left brackets l++; if(ctr[i]==')') //Number of existing right parentheses r++; if(l>n/2||r>n/2){ System.out.println(":("); return; } } l=n/2-l;//Need to let? To become (a quantity) for(int i=0;i<n;i++){ if(ctr[i]=='?'&&l!=0){ //First fill in the left bracket ctr[i]='('; l--; }else if(ctr[i]=='?'){ //Fill in the right bracket with the left bracket ctr[i]=')'; r++; } } l=0; for(int i=0;i<n;i++){ if(ctr[i]=='(')l++; if(ctr[i]==')')l--; if(l<0||(l==0&&i!=n-1)){//If the number of right parentheses is greater than the number of left parentheses in the first k, the true prefix matches. //If the number of left and right parentheses is equal but the last one of the strings is not read, the true prefix matches. System.out.println(":("); return; } } if(l>0){//If there are left parentheses left after traversal, the whole string cannot match. System.out.println(":("); }else{ for(int i=0;i<n-1;i++){ out.print(ctr[i]); //At first, I used syso to output directly. It seems that the output is too large. I used PrintWriter 187ms to do this. //Almost Mental Explosion } out.flush(); System.out.println(ctr[n-1]); } sc.close(); } }