zoukankan      html  css  js  c++  java
  • 堆积木----vector防止内存超限

    蒜头君有 nn 块积木,编号分别为 11 到 nn。一开始,蒜头把第 ii 块积木放在位置 ii。蒜头君进行 mm 次操作,每次操作,蒜头把位置 bb 上的积木整体移动到位置 aa 上面。比如 11 位置的积木是 11,22 位置的积木是 22,那么把位置 22 的积木移动到位置 11 后,位置 11 上的积木从下到上依次为 1,21,2。

    输入格式

    第一行输入 22 个整数 n,m(1 le n le 10000, 0 le m le 10000)n,m(1n10000,0m10000)。

    接下来 mm 行,每行输入 22 个整数 a, b(1 le a, b le n)a,b(1a,bn),如果aa,bb 相等则本次不需要移动。

    输出格式

    输出 nn 行,第 ii 行输出位置 ii 从下到上的积木编号,如果该行没有积木输出一行空行。

    样例输入1

    2 2
    1 2
    1 2

    样例输出1

    1 2
    
    

    样例输入2

    4 4
    3 1
    4 3
    2 4
    2 2

    样例输出2

    2 4 3 1
    
    

    这道题用vector计算很简单。但是会存在内存超限的问题。
    #include<bits/stdc++.h>
    using namespace std;
    vector<int> a[10005];
    void mov(int to,int from)
    {
        for(int i=0;i<a[from].size();i++)
        {
            a[to].push_back(a[from][i]);
        }
        /*vector<int> x;
        a[from].swap(x);*/
        a[from].clear();  
    }
    int main()
    {
    
    
        int n,m;
        cin>>n>>m;
    
        for(int i=1;i<=n;i++)
            a[i].push_back(i);
        for(int i=0;i<m;i++)
        {
            int from,to;
            cin>>to>>from;
            if(from!=to)
                mov(to,from);
        }
        for(int i=1;i<=n;i++)
        {
            for(int j=0;j<a[i].size();j++)
            {
                cout<<a[i][j];
                if(j!=a[i].size()-1) cout<<" ";
            }
            cout<<endl;
        }
        return 0;
    }

    使用注释中的的清空方法,可以释放掉内存。从而避免内存超限。

  • 相关阅读:
    汇编实现点亮Led灯(2440)
    BootLoader(2440)核心初始化代码
    学习单片机的正确方法(转载)
    ARM-汇编指令集(总结)
    BootLoader的架构设计
    统计单词数(WordCount)
    OPcache
    phpcon china 2017听讲总结
    php-fpm进程内存泄漏
    mysql字符串的隐式转换导致查询异常
  • 原文地址:https://www.cnblogs.com/superxuezhazha/p/6390757.html
Copyright © 2011-2022 走看看