堆积木 vector 清空内存

问题

蒜头君有 n 块积木,编号分别为 1 到 n。一开始,蒜头把第 i 块积木放在位置 i。蒜头君进行 m 次操作,每次操作,蒜头把位置 b 上的积木整体移动到位置 a 上面。比如 1 位置的积木是 1,2 位置的积木是 2,那么把位置 2 的积木移动到位置 1 后,位置 1 上的积木从下到上依次为 1,2。

输入格式

第一行输入 2 个整数 n,m(1≤n≤10000,0≤m≤10000)。

接下来 m 行,每行输入 2 个整数 a,b(1≤a,b≤n),如果a,b 相等则本次不需要移动。

输出格式

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

样例输入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<int>tt;
 mu[b].swap(tt);//进行vector的强制内存释放


mu[b].clear();//只是清空vector,并不会清空内存开的内存

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <vector>
#include <stack>
using namespace std; 
const int inf=0x3f3f3f3f;

vector<int> mu[10005];
int n,m;

int main(){
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		mu[i].push_back(i); 
	for(int i=1;i<=m;i++){
		int a,b;
		scanf("%d%d",&a,&b);
		if(a==b||mu[b].empty())	continue;
		for(int j=0;j<mu[b].size();j++)
			mu[a].push_back(mu[b][j]);
		vector<int>tt;
        mu[b].swap(tt);//进行vector的强制内存释放
		//mu[b].clear();//只是清空vector,并不会清空内存开的内存
	}
	for(int i=1;i<=n;i++){
		if(!mu[i].empty())	
			for(int j=0;j<mu[i].size();j++)
				printf("%d ",mu[i][j]);
		printf("\n");
	}
	return 0;
}
/*
2 2
1 2
1 2

4 4
3 1
4 3
2 4
2 2
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值