当前位置:网站首页>1161 Merging Linked Lists

1161 Merging Linked Lists

2022-06-23 07:03:00 The day the flowers fall

The question

Given two linked lists , Find the shortest , Then insert it into the long one , Insert a short one every two , A long length must be more than twice as long as a short one .

Code

#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>

using namespace std;

const int N = 1e6;

struct node
{
    
    int add;
    int data;
    int ne;
}node[N];


int main()
{
    
    int L1, L2, n;
    cin >> L1 >> L2 >> n;
    for (int i = 1; i <= n; i++)
    {
    
        int a, b, c;
        cin >> a >> b >> c;
        node[a] = {
    a, b, c};
    }
    vector<int> l1, l2;
    int t = L1;
    while (t != -1)
    {
    
        l1.push_back(t);
        t = node[t].ne;
    }
    t = L2;
    while (t != -1)
    {
    
        l2.push_back(t);
        t = node[t].ne;
    }
    if (l1.size() < l2.size()) l1.swap(l2);
    reverse(l2.begin(), l2.end());
    // for (int i = 0; i < l1.size(); i++) cout << l1[i] << endl;
    vector<int> res;
    int cnt = 0;
    for (int i = 0, j = 0; i < l1.size(); i++)
    {
    
        cnt++;
        res.push_back(l1[i]);
        if (cnt == 2 && j < l2.size()) 
        {
    
            res.push_back(l2[j++]);
            cnt = 0;
        }
    }
    for (int i = 0; i < res.size(); i++)
    {
    
        if (i + 1 == res.size())
        {
    
            cout << setw(5) << setfill('0') << node[res[i]].add << ' ' << node[res[i]].data << ' ' << -1 << endl;
        }
        else
        {
    
            cout << setw(5) << setfill('0') << node[res[i]].add << ' ' << node[res[i]].data << ' ' << setw(5) << setfill('0') << node[res[i + 1]].add << endl;
        }
    }
    return 0;
}
原网站

版权声明
本文为[The day the flowers fall]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230528522490.html