解题思路:
使用一个数组作为顺序栈,将输入的糖果与栈顶元素进行比较,是否存在该种组合,不存在则元素入栈,存在则更新糖果为组合数,然后继续与栈顶元素比较。
注意事项:
参考代码:
#include <stdio.h> int findCombination(int comb[][3], int m, int x1, int x2) { int find = -1; for (int j = 0; j < m; j++) { if ((comb[j][0] == x1 && comb[j][1] == x2) || (comb[j][0] == x2 && comb[j][1] == x1)) { find = j; break; } } return find; } int main() { // 输入n,m int n, m; scanf("%d %d", &n, &m); // 输入m种组合 int comb[m][3]; for (int i = 0; i < m; i++) { scanf("%d %d %d", &comb[i][0], &comb[i][1], &comb[i][2]); } // 获取糖果数 int k; scanf("%d", &k); int stack[k]; // 栈数组 int top = -1; // 栈顶元素指针 int candy; for (int i = 0; i < k; i++) { scanf("%d", &candy); // 获取输入的糖果 if (top == -1) { // 栈空,元素直接入栈 stack[++top] = candy; } else { while (top > -1) { // 栈非空 int x1 = stack[top]; // 获取栈顶元素 int x2 = candy; int find = findCombination(comb, m, x1, x2); // 根据x1,x2从组合中查找 if (find < 0) { // 不存在x1,x2的组合 break; } else { top--; // 弹出栈顶元素 candy = comb[find][2]; // 更新组合数 } } stack[++top] = candy; // 没有与之匹配的栈顶元素,入栈 } } // 依次输出栈中元素 for (int i = 0; i <= top; i++) { printf("%d ", stack[i]); } return 0; }
0.0分
0 人评分
假币问题 (C++代码)(向上取整的一种处理方式)浏览:1660 |
C语言训练-计算1977!* (C语言代码)浏览:891 |
C语言程序设计教程(第三版)课后习题8.1 (Java代码)浏览:776 |
【回文数(二)】 (C++代码)浏览:865 |
C语言考试练习题_排列 (C语言代码)浏览:1315 |
C语言训练-素数问题 (C语言代码)浏览:1654 |
【亲和数】 (C语言代码)浏览:492 |
小明A+B (C语言代码)浏览:1247 |
printf基础练习2 (C语言代码)浏览:305 |
2003年秋浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:654 |