1. 程式人生 > 其它 >1074 Reversing Linked List (25 分)

1074 Reversing Linked List (25 分)

#include <bits/stdc++.h>
#define LOCAL
using namespace std;

template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef LOCAL
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif

#define vec vector
#define ll long long
#define ld long double
#define sza(x) ((int)x.size())
#define all(a) (a).begin(), (a).end()

const int MAX_N = 1e5 + 5;
const ll MOD = 1e9 + 7;
const ll INF = 1e9;
const ld EPS = 1e-9;

map<int, pair<int, int>> li;
int start, n, k;

int dfs(int add){
    if(add == -1) return -1;
    // cout << add << endl;
    int e = add;
    int cnt = 1;
    while(cnt < k && li[e].second != -1){
        e = li[e].second;
        cnt ++;
    }
    if(cnt < k){
        return add;
    }
    int p = li[e].second;
    int u = add, nxt = li[u].second;
    while(u != e){
        int nnxt = li[nxt].second;
        li[nxt].second = u;
        u = nxt;
        nxt = nnxt;
    }
    li[add].second = dfs(p);
    return u;
}

void solve() {
    cin >> start >> n >> k;
    for(int i = 0; i < n; i ++){
        int a, b, c;
        cin >> a >> b >> c;
        li[a] = {b, c};
    }
    int add = dfs(start);
    while(add != -1){
        printf("%05d %d ", add, li[add].first);
        if(li[add].second == -1) puts("-1");
        else printf("%05d\n", li[add].second);
        // cout << add << ' ' << li[add].first << ' ' << li[add].second << endl;
        add = li[add].second;
    }
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int tc = 1;
    // cin >> tc;
    for (int t = 1; t <= tc; t++) {
        // cout << "Case #" << t << ": ";
        solve();
    }
}