zoukankan      html  css  js  c++  java
  • PAT 1074

    链接:http://www.patest.cn/contests/pat-a-practise/1074

    反转链表,但是PAT上的链表题(其实总共也就两道题)都是可以使诈的,比如list sorting,拿到了数据之后,记录好所有node的val和cur_address,排个序然后再依次打出来就好了... 比起用归并写简单太多也不容易错太多

    这道题也是用使诈的方法更不容易错,记录下来每一个节点的值,然后再用栈和vector将结果拿到,注意当n % k == 0时候的情况。

    #include <fstream>
    #include <iostream>
    #include <vector>
    #include <string>
    #include <stack>
    
    using namespace std;
    
    //#define OJ
    
    #ifdef OJ
    #define fin cin
    #else
    ifstream fin("in.txt");
    #endif
    
    struct Node{
    	int cur_address;
    	int val;
    	int next_address;
    };
    
    int main(){
    	string start;
    	int	n, k;
    	fin >> start >> n >> k;
    
    	vector<Node> nodes(100000);
    
    	for (int i = 0; i < n; i++){
    		Node tmp;
    		string s1, s2;
    
    		fin >> s1 >> tmp.val >> s2;
    		tmp.cur_address = atoi(s1.c_str());
    		tmp.next_address = atoi(s2.c_str());
    
    		nodes[tmp.cur_address] = tmp;
    	}
    
    	int start_idx = atoi(start.c_str());
    	int cur_address = start_idx;
    	vector<int> path;
    
    	while (start_idx != -1){
    		path.push_back(start_idx);
    		start_idx = nodes[start_idx].next_address;
    	}
    
    	vector<int> res;
    	int idx = 0;
    	n = path.size();
    	for (; idx + k - 1 < n; idx += k){
    		stack<int> node_stack;
    		for (int i = 0; i < k; i++){
    			node_stack.push(path[idx + i]);
    		}
    		while (!node_stack.empty()){
    			int tmp = node_stack.top();
    			res.push_back(tmp);
    			node_stack.pop();
    		}
    	}
    	for (; idx < n; idx++){
    		res.push_back(path[idx]);
    	}
    
    	for (int i = 0; i < n - 1; i++){
    		printf("%05d %d %05d
    ", nodes[res[i]].cur_address, nodes[res[i]].val, nodes[res[i + 1]].cur_address);
    	}
    	printf("%05d %d %d
    ", nodes[res[n - 1]].cur_address, nodes[res[n - 1]].val, -1);
    
    	return 0;
    }
    

      

  • 相关阅读:
    PHP 使用 ElasticSearch
    PHP面试题目
    MySQL取得某一范围随机数
    Git版本控制的基本命令
    PHP中array_merge和array相加的区别分析
    nginx服务器常见错误代码500、501、502、503、504、505
    Laravel小项目之第4节 Laravel-通过表单实现新增及操作状态提示功能
    前端基础 jQuery
    前端基础 DOM & BOM
    前端基础 & 初识JS(JavaScript)
  • 原文地址:https://www.cnblogs.com/EpisodeXI/p/4128557.html
Copyright © 2011-2022 走看看