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;
    }
    

      

  • 相关阅读:
    细看运维85条军规,是否触动了你内心深处那根弦?
    SQL语句的CRUD
    sqlserver数据库类型对应Java中的数据类型
    Struts2文件上传--多文件上传(插件uploadify)
    web.xml文件详解
    关于Java的散列桶, 以及附上一个案例-重写map集合
    hibernate多表查询封装实体
    spring的7个模块
    Struts标签库详解【3】
    Struts标签库详解【2】
  • 原文地址:https://www.cnblogs.com/EpisodeXI/p/4128557.html
Copyright © 2011-2022 走看看