2.6学习总结

洛谷1241代码:

应用栈后进先出的特性解决

(只有48,未ac)

#include 
#include 
#include 
#define MAX_SIZE 1000
typedef struct {
    char data[MAX_SIZE];
    int top;
} Stack;
//初始化
void initStack(Stack* s) {
    s->top = -1;
}
//进栈
void push(Stack* s, char c) {
    if (s->top < MAX_SIZE - 1) {
        s->data[++(s->top)] = c;
    }
}
//出栈
char pop(Stack* s) {
    if (s->top >= 0) {
        return s->data[(s->top)--];
    }
    return '\0';
}
//遍历
char peek(Stack* s) {
    if (s->top >= 0) {
        return s->data[s->top];
    }
    return '\0';
}
//匹配
int isMatchingPair(char left, char right) {
    return (left == '(' && right == ')') || (left == '[' && right == ']');
}
//修复
void fixUnmatched(char* s) {
    Stack stack;
    initStack(&stack);
    int len = strlen(s);
    int* matched = (int*)calloc(len, sizeof(int));
    for (int i = 0; i < len; i++) {
        if (s[i] == '(' || s[i] == '[') {
            push(&stack, i);
        }
        else if (s[i] == ')' || s[i] == ']') {
            if (stack.top >= 0 && isMatchingPair(s[peek(&stack)], s[i])) {
                matched[pop(&stack)] = 1;
                matched[i] = 1;
            }
        }
    }
    for (int i = len - 1; i >= 0; i--) {
        if (!matched[i]) {
            if (s[i] == '(' || s[i] == ')') {
                printf("()");
            }
            else if (s[i] == '[' || s[i] == ']') {
                printf("[]");
            }
        }
        else {
            printf("%c", s[i]);
        }
    }
    free(matched);
}
int main() {
    char s[MAX_SIZE];
    scanf("%s", s);
    fixUnmatched(s);
    return 0;
}

洛谷p4913题解

采用bfs广搜

#include
#include
#define max 1000001
typedef struct {
	int left;
	int right;
}node;
node tree[max];
int depth[max];
int main() {
	int n;
	scanf("%d", &n);
	for (int i = 1;i <= n;i++) {
		scanf("%d %d", &tree[i].left, &tree[i].right);
	}
	int maxdepth = 0;
	int queue[max];
	int front = 0, rear = 0;
	queue[rear++] = 1;
	depth[1] = 1;
	while (front < rear) {
		int current = queue[front++];
		if (depth[current] > maxdepth) {
			maxdepth = depth[current];
		}
		if (tree[current].left != 0) {
			queue[rear++] = tree[current].left;
			depth[tree[current].left] = depth[current] + 1;
		}
		if (tree[current].right != 0) {
			queue[rear++] = tree[current].right;
			depth[tree[current].right] = depth[current] + 1;
		}
	}
	printf("%d", maxdepth);
	return 0;
}

 

 

你可能感兴趣的:(学习)