0%

算法竞赛入门经典(第2版) 6-11UVa10410 6-13UVa215

最近刷题量大,不高兴写题解了。以后算竟的题目可能只是跳着做做了。

题目:6-11 UVa10410 - Tree Reconstruction

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//UVa10410 - Tree Reconstruction
//Accepted 0.000s
#include<iostream>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 1000 + 6;
int n, bfs[maxn];

int main()
{
while (cin >> n) {
int now;
for (int i = 0; i < n; ++i) {
cin >> now;
bfs[now] = i;
}
stack<int> st;
vector<int> vc[maxn];
cin >> now;
st.push(now);
for (int i = 1; i < n; ++i){
cin >> now;
while (!st.empty()) {
int top = st.top();
if (bfs[now] > bfs[top]+1 || st.size()==1) {
vc[top].push_back(now);
st.push(now);
break;
}
else {
st.pop();
}
}
}
for (int i = 1; i <= n; ++i) {
cout << i << ": ";
for (const auto& e : vc[i])
cout << e << ' ';
cout << '\n';
}
}
return 0;
}


题目:6-13 UVa215 - Spreadsheet Calculator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//UVa215 - Spreadsheet Calculator
//Accepted 0.000s
#include<iostream>
#include<iomanip>
#include<sstream>
#include<string>
#include<cstring>
using namespace std;
int N, M;
int vl[24][14]; //value
string xp[24][14]; //expr
bool ve[24][14]; //kind
bool vis[24][14];

int val(int x, int y) {
if (ve[x][y]) return vl[x][y];
if (vis[x][y]) return -1;
int op = 1;
vl[x][y] = 0;
vis[x][y] = true;
string &now = xp[x][y];
for (int i = 0; i < xp[x][y].size(); ++i) {
if (now[i] >= '0'&&now[i] <= '9') {
int tmp = 0;
while (now[i] >= '0'&&now[i] <= '9') {
tmp *= 10;
tmp += now[i] - 0x30;
++i;
}
--i;
vl[x][y] += tmp*op;
}
else if (now[i] >= 'A'&&now[i] <= 'Z') {
vl[x][y] += val(now[i] - 'A', now[i + 1] - '0')*op;
if (!ve[now[i] - 'A'][now[i + 1] - '0']) return -1;
++i;
}
else {
op = (now[i] == '+' ? 1 : -1);
}
}
ve[x][y] = 1;
return vl[x][y];
}

int main()
{
//freopen("in.txt", "r", stdin);//----------------------------------
while (cin >> N >> M && N != 0 && M != 0) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
cin >> xp[i][j];
if (xp[i][j][0] >= 'A'&&xp[i][j][0] <= 'Z') {
ve[i][j] = false;
}
else {
ve[i][j] = true;
istringstream in(xp[i][j]);
in >> vl[i][j];
}
}
}
int cnt = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (ve[i][j]) continue;
memset(vis, 0, sizeof(vis));
val(i, j);
if (!ve[i][j]) ++cnt;
}
}
if (cnt) {
for (int i = 0; i < N; ++i) {
for (int j = 0; j < M; ++j) {
if (ve[i][j]) continue;
cout << char(i + 'A') << char(j + '0') << ": " << xp[i][j] << '\n';
}
}
}
else {
cout << ' ';
for (int i = 0; i < M; ++i)
cout << setw(6) << i;
cout << '\n';
for (int i = 0; i < N; ++i) {
cout << char('A' + i);
for (int j = 0; j < M; ++j)
cout << setw(6) << vl[i][j];
cout << '\n';
}
}
cout << endl;
}
return 0;
}