L2-002
L2-022
把链表一类的放在一起写好一点….
对于链表一类的题目都用一个结构体去表示一个结点, 并且遍历的时候都是通过遍历当前的编号来的, 不要用遍历下一个编号之类的来做. 然后结点中要维护好哪些值就在结构体中添加哪些值即可, 最常见的就是值和下一个节点了, 然后用好了结构体表示后就比较好写的….
L2–002: 这个直接模拟做就好了, 逻辑清晰点……
AC Code
const int maxn = 1e5+5;
struct node {
int w, next;
}e[maxn], a[maxn], b[maxn];
int ra = -1, rb = -1;
map<int, int>mp;
void solve()
{
int root, n;
cin >> root >> n;
for (int i = 1 ; i <= n ; i ++) {
int u, w, v;
cin >> u >> w >> v;
e[u].w = w; e[u].next = v;
}
int p = root;
int st1 = -1, st2 = -1;
while(p != -1) {
if (mp[abs(e[p].w)]) {
if (rb == -1) {
rb = p; st2 = p;
b[rb].w = e[p].w;
b[rb].next = -1;
}
else {
b[rb].next = p;
rb = p;
b[rb].w = e[p].w;
b[rb].next = -1;
}
}
else {
if (ra == -1) {
ra = p; st1 = p;
a[ra].w = e[p].w;
a[ra].next = -1;
}
else {
a[ra].next = p;
ra = p;
a[ra].w = e[p].w;
a[ra].next = -1;
}
}
mp[abs(e[p].w)] = 1;
p = e[p].next;
}
if (st1 != -1) {
while(st1 != -1) {
printf("%05d %d ", st1, a[st1].w);
if (a[st1].next == -1) printf("-1\n");
else printf("%05d\n", a[st1].next);
st1 = a[st1].next;
}
}
if (st2 != -1) {
while(st2 != -1) {
printf("%05d %d ", st2, b[st2].w);
if (b[st2].next == -1) printf("-1\n");
else printf("%05d\n", b[st2].next);
st2 = b[st2].next;
}
}
}
L2 - 022 :
思路: 这个明显就需要用到一个结点的前驱, 所以在结构体中多加一个参数表示前驱, 然后同时从前面和后面开始做, 用一个计数器判断此时应该从前面取还是后面取, 唯一的坑点就是链表可以不止一个, 虽然题目说的一个, 所以还需要好给定头结点的那个链表取出来再做上面的操作才是对的.
AC Code
struct node {
int st, w, next;
}s[maxn], e[maxn], a[maxn];
void solve()
{
int root, n;
cin >> root >> n;
for (int i = 1 ; i <= n ; i ++) {
int u, w, v;
cin >> u >> w >> v;
s[u].w = w; s[u].next = v;
if (v != -1) s[v].st = u;
}
int h = root, k = 0;
int l = root, r;
while(h != -1) {
r = h;
e[h] = node{s[h].st, s[h].w, s[h].next};
++k; h = s[h].next;
}
int cnt = 1, st = r;
for (int i = 1 ; i <= k ; i ++) {
if (cnt & 1) {
a[r].next = l;
a[r].w = e[r].w;
r = e[r].st;
}
else {
a[l].next = r;
a[l].w = e[l].w;
l = e[l].next;
}
++ cnt;
}
if (n & 1) a[l].next = -1;
else a[r].next = -1;
while(st != -1) {
printf("%05d %d ", st, a[st].w);
if (a[st].next == -1) printf("-1\n");
else printf("%05d\n", a[st].next);
st = a[st].next;
}
}
通过这两题, 就想说CCCC的链表题如何去建立它, 去更好的解决它……