首页 > 试题广场 >

Linked List Sorting (25)

[编程题]Linked List Sorting (25)
  • 热度指数:4455 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
A linked list consists of a series of structures, which are not necessarily adjacent in memory. We assume that each structure contains an integer key and a Next pointer to the next structure. Now given a linked list, you are supposed to sort the structures according to their key values in increasing order.

输入描述:
Each input file contains one test case. For each case, the first line contains a positive N (5) and an address of the head node, where N is the total number of nodes in memory and the address of a node is a 5-digit positive integer.  NULL is represented by -1.
Then N lines follow, each describes a node in the format:
Address Key Next
where Address is the address of the node in memory, Key is an integer in [-105, 105], and Next is the address of the next node. It is guaranteed that all the keys are distinct and there is no cycle in the linked list starting from the head node.


输出描述:
For each test case, the output format is the same as that of the input, where N is the total number of nodes in the list and all the nodes must be sorted order.
示例1

输入

5 00001
11111 100 -1
00001 0 22222
33333 100000 11111
12345 -1 33333
22222 1000 12345

输出

5 12345
12345 -1 00001
00001 0 11111
11111 100 22222
22222 1000 33333
33333 100000 -1
思路 地址映射把一条有效的链条找到,然后排序这个链条然后输出。
#include <iostream>
#include <fstream>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;

#ifndef debug
ifstream ifile("case.txt");
#define cin ifile
#endif


struct link
{
    int data;
    int adr;
    int nAdr;
};

bool Cmp(struct link & a, struct link & b)
{
    return a.data < b.data;
}

int main()
{
    int n, startAdr;
    while (cin >> n >> startAdr)
    {
        vector<struct link> v(n);
        int mark[100000] = { 0 };// 地址映射
        vector<struct link> valid;
        int index = 0;
        for (int i = 0; i < n; i++)
        {
            int tmp;
            cin >> v[i].adr >> v[i].data >> v[i].nAdr;
            mark[v[i].adr] = i;
            if (v[i].adr == startAdr)
            {
                index = i;
            }
        }
        //int validNum = 0;
        for (int i = index; v[i].nAdr!=-1;)
        {
            valid.push_back(v[i]);
            i = mark[v[i].nAdr];
            index = i;
        }
        valid.push_back(v[index]);// 添加 -1这个节点
        sort(valid.begin(), valid.end(), Cmp);
        // 输出
        if (startAdr == -1)
        {
            cout << 0 << " " << -1 << endl;
            continue;
        }
        cout << valid.size() << " " << setfill('0') << setw(5) << valid[0].adr << endl;
        for (int i = 0; i < valid.size(); i++)
        {
            cout << setfill('0') << setw(5) << valid[i].adr;
            if (i != valid.size() - 1)
                cout << " " << valid[i].data << " " << setfill('0') << setw(5) << valid[i + 1].adr << endl;
            else
                cout << " " << valid[i].data << " " << -1 << endl;
        }
    }
    system("pause");
}

发表于 2018-08-29 10:01:03 回复(0)
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

#define MAX 100009

//我习惯邓俊辉版数据结构的双链表(有不存数据的头、尾节点),各种操作都很方便
//不过本题只需要把链表更新为双链表,然后进行插入排序即可
int N, key[MAX], nex[MAX], pri[MAX], first;
int len = 1;

void read_list() {
	memset(nex, -1, sizeof(nex));
	memset(pri, -1, sizeof(pri));

	cin >> N >> first; int ad;
	for (int i = 1; i <= N; ++i) {
		cin >> ad; 
		cin >> key[ad] >> nex[ad];
	}
}

void set_prior() {//把单链表变为双链表,顺便统计实际在链表中的节点个数
	int p = first, q = nex[first];
	while (q != -1) {
		++len;
		pri[q] = p;
		p = q; q = nex[q];
	}
}

void insertion_sort() {//插入排序,循环内两个if-else是为了应对链表两端的特殊情况
					   //如果有不存储数据的头尾节点,则这两个if-else都可以简化,不过本题就不讨论这个了
	for (int p = nex[first]; p != -1; p = nex[p])//从第2个节点到最后一个节点
		if (key[pri[p]] > key[p]) {//发现逆序,则
			int q = pri[p]; int pp = q;
			//跳出循环后,q指向<=key[p]的最右者
			for (; q != -1 && key[q] > key[p]; q = pri[q]);

			//摘除p
			if (nex[p] != -1) { nex[pp] = nex[p]; pri[nex[p]] = pp; }//常规
			else nex[pp] = -1;//p指向最后一个节点本身

			//插入q后方
			pri[p] = q; 
			if (q != -1) { nex[p] = nex[q]; pri[nex[q]] = p; nex[q] = p; }//常规
			else { nex[p] = first; pri[first] = p; first = p; }//q指向第一个节点的前端

			p = pp;//重置p,以便进行下一轮遍历
		}
}

void out_res() {
	if (first != -1) {//有一个坑爹的样例把头节点设置成NULL
		printf("%d %05d\n", len, first);
		int p = first, q = nex[first];
		while (q != -1) {
			printf("%05d %d %05d\n", p, key[p], q);
			p = q; q = nex[q];
		}
		printf("%05d %d %d", p, key[p], q);
	}
	else cout << 0 << " " << -1;
}

int main()
{
	read_list();
	set_prior();
	insertion_sort();
	out_res();

	return 0;
}

编辑于 2021-03-16 04:56:49 回复(0)
a = input().split()
if a[1] == '-1':
    print(0,-1)
    import sys
    sys.exit(0)
d,e = {},{}
for i in range(int(a[0])):
    b = input().split()
    d[b[0]] = b[1:]
while a[1] != "-1":
    e[int(d[a[1]][0])],a[1] = [a[1],d[a[1]][1]],d[a[1]][1]
m = sorted(e)
print(len(e),e[m[0]][0])
for i in range(len(e) - 1):
    print(e[m[i]][0],m[i],e[m[i + 1]][0])
print(e[m[-1]][0],m[-1],-1)

编辑于 2020-07-13 22:04:17 回复(0)

#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
#include <vector>
#include <map>
#include <list>
using namespace std;

//1052 Linked List Sorting
//按key升序
//坑,有些结点是干扰项,并不在可联通主链上
//坑,list不能用std::sort,要用自己的list::sort
//坑,list使用erase后,原来的迭代器失效,不能直接++继续遍历,需要中介。
//这个算法O(NlogN)
//用cin运气好可以380ms卡过去pat.4 (限制400ms),成功概率大概一半一半。
//改成用scanf之后,成功率大大提高,330ms左右过关。

//测试用例:
//1 - 1
//00000 5 - 1
//
//对应输出应该为:
//
//0 - 1

map<string, string> child;
map<string, int> legal;

class node {
public:
    string add;
    int key;
    string next;
};

list<node> li;

bool mycmp(const node &a, const node &b) {
    return a.key < b.key;
}

int main() {
    int n; string ftadd;
    cin >> n >> ftadd;

    //输入
    int  key; string add, next;
    for (int i = 0; i < n; ++i) {
        char a[10],b[10];
        scanf("%s%d%s", a, &key, b);
        add = a;
        next = b;
        li.push_back({ add,key,next });
        child[add] = next;
    }

    //查找合法结点,O(NlogN)
    string p = ftadd;
    while (p != "-1") {
        legal[p] = 1;
        //牛客有个case是,首地址不在输入序列里,find是找不到的。
        if (child.find(p) != child.end()) { p = child[p]; }
        else { p = "-1"; }
    }

    //过滤非法结点O(NlogN)
    list<node>::iterator ii;
    for (auto it = li.begin(); it != li.end(); ) {
        //查找不存在的数时,会直接初始化为0,速度比map.find快
        if (legal[it->add] != 1) {
            ii = it;
            it++;
            li.erase(ii);
        }
        else {
            it++;
        }
    }

    //为空说明没有元素了,直接结束
    if (li.empty()) { cout << "0 -1"; return 0; }

    //排序O(NlogN)
    li.sort(mycmp);

    //输出
    cout << li.size() << " " << li.front().add << endl;
    for (auto i = li.begin(); i!=li.end(); ++i) {
        ii = i; ii++;
        if (ii != li.end()) { i->next = ii->add; }
        else { i->next = "-1"; }
        cout << i->add << " " << i->key << " " << i->next << endl;
    }

    return 0;
}


编辑于 2019-08-15 10:18:54 回复(0)
思路就是先把所有节点读进来(因为不读完没办法判断节点在不在链表里所以没办法一边读一遍删除多余节点,所以这个空间是必须的),读取的时候做了一个map<int,int>把address映射为index。
然后从Head地址(翻译成index)开始到链尾把index压入一个vector<int>做输出准备。
对vector<int>做自定义排序(根据index对应的Key升序)
然后对vector<int>存储的index做依次输出 不用改next值,只要输出下一个的add就好

代码如下:
#include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;

typedef struct sNode {
	int Add, Key, Next;
	sNode(int add, int key, int next) :
		Add(add), Key(key), Next(next) {}
}Node;

vector<Node> List;
inline bool cmp(int A, int B) { return List[A].Key < List[B].Key; }

int main(int argc, const char* argv[]) {
	ios::sync_with_stdio(false);
	map<int, int> add2index;
	int N, Head;
	cin >> N >> Head;
	for (int i = 0;i < N;i++) {
		int add, val, next;
		cin >> add >> val >> next;
		List.push_back(Node(add, val, next));
		add2index[add] = i;
	}
	int p = Head;
	vector<int> Output;
	while (p + 1) {
		Output.push_back(add2index[p]);
		p = List[add2index[p]].Next;
	}
	sort(Output.begin(), Output.end(), cmp);
	int len = Output.size() - 1;
	if (len + 1) {
		printf("%d %05d", len + 1, List[Output[0]].Add);
		for (int i = 0;i < len;i++)
			printf("\n%05d %d %05d", List[Output[i]].Add, List[Output[i]].Key, List[Output[i + 1]].Add);
		printf("\n%05d %d -1", List[Output[len]].Add, List[Output[len]].Key);
	}
	else cout << "0 -1";

	//system("pause");
	return 0;
}

编辑于 2017-02-13 17:18:36 回复(0)
本题主要考察排序。
有两点需要注意:
1.链表可能不只一个,此时只需将第一个进行排序即可;
2.链表为空时 需要输出“0 -1”。
发表于 2015-07-06 20:53:28 回复(0)
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=100010;
struct Node{                                                 //定义静态链表
    int next,key;
}node[maxn];
int order[maxn];                                             //开一个数组按顺序存储有效结点
bool cmp(int a,int b){                                       //按要求以key从小到大排序
    return node[a].key<node[b].key;
}
int main(){
    int n,head,num,count=0;
    cin>>n>>head;
    for(int i=0;i<n;i++){
        cin>>num;
        cin>>node[num].key>>node[num].next;
    }
    if(head==-1){                                            //结点全部无效,不在链表中,输出特例并退出程序
        printf("0 -1");
        return 0;
    } 
    for(int i=0,num=head;num!=-1;num=node[num].next,i++){    //以给出首地址遍历链表,将有效结点的地址按顺序存储到数组中
        count++;
        order[i]=num;
    }
    n=count;
    sort(order,order+n,cmp);                                 //给链表结点按key从小到大排序
    printf("%d %05d\n",n,order[0]);                          //输出链表结点个数以及排序后的首地址
    for(int i=0;i<n;i++){
        printf("%05d %d ",order[i],node[order[i]].key);
        if(i!=n-1) printf("%05d\n",order[i+1]);
        else printf("-1\n");                                 //链表最后一个结点的next为null即-1
    }
    return 0;
} 

编辑于 2019-01-07 16:19:07 回复(0)
#include<bits/stdc++.h>
using namespace std;

const int Max=1e5+10;
struct Node {
    int address;
    int data;
    int next;
    bool flag;
} node[Max];

bool cmp(Node a,Node b) {
    if(!a.flag||!b.flag) {
        return a.flag>b.flag;
    } else {
        return a.data<b.data;
    }
}

int main() {
    for(int i=0; i<Max; i++) {
        node[i].flag=0;
    }
    int n,begin;
    while(cin>>n>>begin) {
        int address,data,next;
        for(int i=0; i<n; i++) {
            cin>>address>>data>>next;
            node[address].address=address;
            node[address].data=data;
            node[address].next=next;
        }
        int count=0;
        for(int p=begin; p!=-1; p=node[p].next) {
            node[p].flag=1;
            count++;
        }
        if(count==0) {
            printf("0 -1\n");
        } else {
            sort(node,node+Max,cmp);
            printf("%d %05d\n",count,node[0].address);
            for(int i=0; i<count; i++) {
                if(i==count-1) {
                    printf("%05d %d -1\n",node[i].address,node[i].data);
                } else {
                    printf("%05d %d %05d\n",node[i].address,node[i].data,node[i+1].address);
                }
            }
        }
    }
    return 0;
}
发表于 2022-10-24 21:34:40 回复(2)
  这题实际上很简单,就是个排序,相当于每个给出的数据创建一个结点,(结点包含当前地址和key)。然后对这些结点排序,但是要注意,他给出的所有结点不一定都在一个链表上,所以要根据给出的头结点来判断那些在这个链表上,因此读取的时候可以用一个map或者一个数组标记一下。

#include<iostream>//  00001->22222->12345->33333->11111->-1
(3742)#include<vector>
#include<algorithm>
(831)#include<map>
using namespace std;
const int maxn = 100000;
struct Node {
	int key;
	int address;
	Node(int k, int a) :key(k), address(a) {}
	Node() :key(-1), address(-1) {}
};
bool cmp(Node a, Node b) {
	return a.key < b.key;
}
int main() {
	int n, head;
	vector<Node>Nodes;
	cin >> n >> head;
	map<int, Node>mymap;
	for (int i = 0; i < n; i++) {
		int address, key, next;
		cin >> address >> key >> next;
		mymap[address] = Node(key, next);//这里map存当前的key和下一个结点的地址
	}
	while (head != -1) {
		Nodes.push_back(Node(mymap[head].key,head));
		head = mymap[head].address;
	}
	sort(Nodes.begin(), Nodes.end(), cmp);
	if (!Nodes.size()) {
		printf("0 -1\n");
	}
	else {
		printf("%d %05d\n", Nodes.size(), Nodes[0].address);//第一个为根
		for (int i = 0; i < Nodes.size() - 1; i++) {
			printf("%05d %d %05d\n", Nodes[i].address, Nodes[i].key, Nodes[i + 1].address);
		}
		printf("%05d %d -1", Nodes[Nodes.size() - 1].address, Nodes[Nodes.size() - 1].key);
	}
}

 
发表于 2020-03-26 12:52:10 回复(0)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct node{
	int ad,key,next;
}no[100005];
bool cmp(node a,node b){
	return a.key<b.key;
}
int main(){
	int n,h;
	cin>>n>>h;
	for(int i=0;i<n;i++){
		int t;cin>>t;
		no[t].ad=t;
		cin>>no[t].key>>no[t].next;
	}
	vector<node> r;
	for(int cur=h;cur!=-1;cur=no[cur].next){
		r.push_back(no[cur]);
	}
	if(r.size()==0) {printf("0 -1");return 0;}
	sort(r.begin(),r.end(),cmp);
	printf("%d %05d\n",r.size(),r[0].ad);
	for(int i=0;i<r.size();i++){
		printf("%05d %d ",r[i].ad,r[i].key);
		if(i==r.size()-1) printf("-1\n");
		else printf("%05d\n",r[i+1].ad);		
	}
	return 0;
}

发表于 2020-01-14 15:21:31 回复(0)
题做多了发现自己代码都比别人短了
#include<stdio.h>

int i,j,N,head,key[100000],next[100000],a[100000];
int Comp(const void*x,const void*y)
{	return key[*(int*)x]-key[*(int*)y];
}

int main()
{
	scanf("%d %d",&N,&head);
	for(i=0;i<N;i++){
		scanf("%d",&j);
		scanf("%d %d",key+j,next+j);
	}
	for(N=0,j=head;j>=0;N++,j=next[j])a[N]=j;
	qsort(a,N,sizeof(int),Comp);
	printf(!N?"%d -1\n":"%d %05d\n",N,a[0]);
	for(i=0;i<N;i++)printf(i==N-1?"%05d %d -1\n":"%05d %d %05d\n",a[i],key[a[i]],a[i+1]);
}


发表于 2019-11-13 14:23:20 回复(0)
有个比较坑的地方就是链表的个数可能为0的情况,第四个测试点就是为0的情况,还有就是打印的是有效的节点的个数,
#include<iostream>
#include<stdlib.h>
#include<algorithm>
using namespace std;

pair<int, int> a[100005];//数据,下一个地址
pair<int, int> b[100005];//数据,当前地址
int main() {
	int n = 0, head = 0, add = 0, index = 0;
	cin >> n >> head;
	for (int i = 0; i < n; i++) {
		scanf("%d", &add);
		scanf("%d%d",&a[add].first,&a[add].second);
	}
	for (;head>=0; head = a[head].second, ++index) {//把链表加入q中
		b[index] = make_pair(a[head].first, head);
	}
	sort(b, b + index);//按照数字的大小排序
	printf("%d",index);//应该是打印链表的个数
	if (index == 0) {//第四个点就是测试链表个数为0的情况的
		printf(" -1\n");//如果输入的数字个数为0
	}
	else {
		printf(" %05d\n",b[0].second);
		for (int i = 0;i < index; i++) {
			printf("%05d %d",b[i].second,b[i].first);
			if (i == index - 1) {
				printf(" -1\n");//打完最后一个一之后就打印换行
			}
			else {
				printf(" %05d\n" ,b[i+1].second);
			}
		}
	}
	system("pause");
	return 0;
}


编辑于 2019-10-23 22:32:50 回复(0)
看了几个答案,全是用sort直接来,在下贴一个链表归并排序的,虽然麻烦些但还是要掌握的(其实代码可以再精简些,但没必要)。
#include<unordered_map>
#include<cstdio>
using namespace std;
class Node{
public:
    int addr;
    int key;
    int nextAddr;
    Node* next;
    Node(int _addr, int _key, int _nextAddr):addr(_addr),key(_key),nextAddr(_nextAddr),next(NULL){}
    Node():next(NULL){}
};
unordered_map<int,Node*> mp;
Node* merge(Node* A, Node* B){
    if(A == NULL) return B;
    if(B == NULL) return A;
    Node* dummy = new Node(-2,0,-1);
    Node* tmp = dummy;
    while(A && B){
        if(A->key < B->key){
            tmp->next = A;
            A = A->next;
        }else{
            tmp->next = B;
            B = B->next;
        }
        tmp = tmp->next;
    }
    tmp->next = (A==NULL? B : A);
    Node* res = dummy->next;
    delete dummy;
    return res;
}
Node* mergeSort(Node* head){
   if(!head || !(head->next)) return head;
   Node *slow=head, *fast = head->next, *partner=head;
   while(fast && fast->next){
       fast = fast->next->next;
       slow = slow->next;
   }
   partner = slow->next;
   slow->next = NULL;
   Node* m1 = mergeSort(head);
   Node* m2 = mergeSort(partner);
   return merge(m1,m2);
}

int main(){
    int N,start,addr,key,nextAddr,count;
    scanf("%d %d",&N,&start);
    Node nodes[N];
    for(int i = 0 ; i < N; i++){
        scanf("%d %d %d",&addr,&key,&nextAddr);
        nodes[i].addr = addr;
        nodes[i].key = key;
        nodes[i].nextAddr = nextAddr;
        mp[addr] = &nodes[i];
    }
    //构建链表
    if(start == -1){//头结点即为NULL的情况
        printf("0 -1");
        return 0;
    }
    Node* head = mp[start];
    count = 1;
    while(head->nextAddr != -1){
        head->next = mp[head->nextAddr];
        head = head->next;
        count++;
    }
    Node* newHead = mergeSort(mp[start]);

    printf("%d %05d\n",count,newHead->addr);
    while(newHead){
        printf("%05d %d",newHead->addr, newHead->key);
        if(newHead->next) printf(" %05d\n",newHead->next->addr);
        else printf(" -1\n");
        newHead = newHead->next;
    }
    return 0;
}


编辑于 2019-01-15 17:12:21 回复(1)
n,start = map(int,input().split())
if start!=-1:
    lst,lst1 = [None,None]*100001,[]
    for i in range(0,n):
        a,b,c = map(int,input().split())
        lst[a]=[b,c]
    while start!=-1:
        lst1.append([start,lst[start][0]])
        start = lst[start][1]      
    lst1.sort(key = lambda x:(x[1]))
    for i in range(0,len(lst1)-1):
        lst1[i].append(lst1[i+1][0])
    print(str(len(lst1))+" "+"%05d"%lst1[0][0])
    for i in range(0,len(lst1)-1):
        print("%05d"%lst1[i][0]+" "+str(lst1[i][1])+" "+"%05d"%lst1[i][2])
    print("%05d"%lst1[len(lst1)-1][0]+" "+str(lst1[len(lst1)-1][1])+" "+"-1")
else:
    print("0 -1")
#要注意本题对算法的复杂度有要求。在提取有效链表的时候需要节省时间的方法。

发表于 2018-12-02 23:17:04 回复(0)
N,M=map(int,input().split())
inList=[None,None]*100005
for i in range(N):
    a,b,c=map(int,input().split())
    inList[a]=[b,c]
L=[]
while M!=-1:
    L.append([M,inList[M][0]])
    M=inList[M][1]
L.sort(key=lambda x:x[1])
if len(L)==0:
    print(0,-1)
else:
    print('{} {:05d}'.format(len(L),L[0][0]))
    for i in range(len(L)-1):
        print('{:05d} {} {:05d}'.format(L[i][0],L[i][1],L[i+1][0]))
    print('{:05d} {} {}'.format(L[-1][0],L[-1][1],-1))

发表于 2018-09-04 15:58:01 回复(0)
static class Node implements Comparable{
        int val;
        String address;
        String next;
        Node(String address,int val,String next){
            this.address = address;
            this.val = val;
            this.next = next;
        }
        
        public void changeNxt(String address) {
            this.next = address;
        }
        
        @Override
        public int compareTo(Object o) {
            // TODO Auto-generated method stub
            Node node = (Node)o;
            return this.val-node.val;
        }
        
    }
    
    public static void main(String[] args) {
        Node[] addr = new Node[100000];
        ArrayList<Node> validnodes = new ArrayList<Node>();
        Scanner scan = new Scanner(System.in);
        int N = scan.nextInt();
        String head = scan.next();
        
        for(int i=0;i<N;i++) {
            String address = scan.next();
            int val = scan.nextInt();
            String next = scan.next();
            Node node = new Node(address,val,next);
            addr[Integer.parseInt(address)] = node;
        }
        
        if(head.equals("-1")) {
            System.out.println("0"+" "+"-1");
            return;
        }
        int p = Integer.parseInt(head);
        while(p!=-1) {
            Node node = addr[p];
            validnodes.add(node);
            p = Integer.parseInt(node.next);
        }
        Collections.sort(validnodes);
        for(int i=0;i<validnodes.size()-1;i++) {
            validnodes.get(i).changeNxt(validnodes.get(i+1).address);;
        }
        validnodes.get(validnodes.size()-1).changeNxt("-1");
        System.out.println(validnodes.size()+" "+validnodes.get(0).address);
        for(int i=0;i<validnodes.size();i++) {
            Node node = validnodes.get(i);
            System.out.print(node.address+" ");
            System.out.print(node.val+" ");
            System.out.println(node.next);
        }
    }
发表于 2018-03-11 16:54:11 回复(0)
/*这题的思路大概就是:先要遍历一遍从开始结点的单链表,标记这些结点为true
然后排序时,先按结点true、false为第一关键字,以其key为第二关键字排序
这样就能保证所有在单链表上的结点在排序结果前面了 */

#include <cstdio>
#include <iostream>
#include <cstring>
#include <cctype>
#include <algorithm>
using namespace std;

const int maxn = 100010;

struct Node
{
int key, next, address;
bool flag;
} node[maxn];

bool cmp(Node a, Node b)
{
if (a.flag == false || b.flag == false)
return a.flag > b.flag;
else
return a.key < b.key;    // 题目要求是升序,我却弄成了从大到小的顺序
}

int main()
{
freopen("C:\\Documents and Settings\\Administrator\\桌面\\data.txt", "r", stdin); // 我把这个and不小心写成了ans怪不得读入不了数据呀呀
    for (int i = 0; i < maxn; i++)
{
node[i].flag = false;
}
int p, n;
int key, address, next;
scanf("%d%d", &n, &p);
for (int i = 0; i < n; i++)
{
scanf("%d%d%d", &address, &key, &next);
node[address].key = key;
node[address].next = next;
node[address].address = address;
}
int count = 0;
while (p != -1)
{
count++;
node[p].flag = true;
p = node[p].next;
}
if (count == 0)
{
printf("0 -1\n");
}
else
{
sort(node, node + maxn, cmp);

printf("%d %05d\n", count, node[0].address);      // 题目要求地址输出5位,我直接输出了
for (int i = 0; i < count; i++)
{
if (i < count - 1)   // 题目要求地址输出5位,我直接输出了
{
printf("%05d %d %05d\n", node[i].address, node[i].key, node[i + 1].address);
}
else
{
printf("%05d %d -1\n", node[i].address, node[i].key);   // 题目要求地址输出5位,我直接输出了
}
}
}
    while (1);
return 0;
}

发表于 2017-09-03 15:18:24 回复(0)
 // 1052.cpp : 定义控制台应用程序的入口点。
//

#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <deque>
#include <cmath>

using namespace std;

struct NODE {
	int addr, data, next;
};

vector<NODE> vec;

bool compare(NODE a, NODE b)
{
	return a.data < b.data;
}

const int maxn = 100010;
int s[maxn], dat[maxn];

int main()
{
	int n, start; scanf("%d%d", &n, &start);
	if (start == -1) {
		printf("0 -1");
		return 0;
	}
	for (int i = 0; i < n; i++) {
		int addr, data, next;
		scanf("%d%d%d", &addr, &data, &next);
		if (addr >= 0) {
			s[addr] = next;
			dat[addr] = data;
		}
	}

	while (start != -1) {
		NODE node;
		node.addr = start;
		node.next = s[node.addr];
		node.data = dat[node.addr];
		vec.push_back(node);
		start = s[start];
	}

	sort(vec.begin(), vec.end(), compare);
	for (int i = 0; i < vec.size() - 1; i++)
		vec[i].next = vec[i + 1].addr;
	if(vec.size() > 0)
		vec[vec.size() - 1].next = -1;

	printf("%d %05d\n", vec.size(), vec[0].addr);
	for (int i = 0; i < vec.size(); i++)
		if (i == vec.size() - 1)
			printf("%05d %d %d\n", vec[i].addr, vec[i].data, vec[i].next);
		else
			printf("%05d %d %05d\n", vec[i].addr, vec[i].data, vec[i].next);
	
    return 0;
}

发表于 2017-03-01 13:03:41 回复(0)

#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<cctype>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<stack>
using namespace std;
const int maxn=100001;
struct NODE{
	int addr,key,next;
	bool fg;
}node[maxn];
bool cmp(NODE a,NODE b){
	if(a.fg==false || b.fg==false)
		return a.fg>b.fg;
	else
		return a.key<b.key;
}
int main(){
	int n,s;
	for(int i=0;i<maxn;i++){
			node[i].fg=false;;
		}
	//	freopen("G:\\PATdata\\A1052.txt","r",stdin);
	cin>>n>>s;
	int addr;
		for(int i=0;i<n;i++){

			cin>>addr;
			cin>>node[addr].key>>node[addr].next;
			node[addr].addr=addr;
		}
		int cnt=0,p=s;
		while(p!=-1){
			node[p].fg=true;
			cnt++;
			p=node[p].next;
		}


	if(cnt!=0){
			sort(node,node+maxn,cmp);
			s=node[0].addr;
			printf("%d %05d\n",cnt,s);
			for(int i=0;i<cnt;i++){
				if(i<cnt-1)
					printf("%05d %d %05d\n",node[i].addr,node[i].key,node[i+1].addr);
				else
					printf("%05d %d -1\n",node[i].addr,node[i].key);
			}

	}else
		printf("0 -1\n");

	return 0;
}

发表于 2017-01-11 11:39:23 回复(0)
啥头像
总体思路:
        1.提取有效节点
        2.按节点的key排序

代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdio.h>

using namespace std;

struct Node{
    int key, address;
    bool operator<(const Node& that) const {
        return (key<that.key);
    }
};

int data[100000][2];

int main()
{
    // 读入数据
    int N, startAddress, address;
    scanf("%d %d", &N, &startAddress);
    while(N--) {
        scanf("%d", &address);
        scanf("%d %d", &data[address][0], &data[address][1]);
    }
    vector<Node> nodes; address = startAddress; Node tempNode;
    while(address != -1) {
        tempNode.key = data[address][0];
        tempNode.address = address;
        nodes.push_back(tempNode);
        address = data[address][1];
    }

    // 排序输出
    sort(nodes.begin(), nodes.end()); int i;
    if(nodes.size()) {
        printf("%d %05d\n", nodes.size(), nodes[0].address);
        for(i=0; i<nodes.size()-1; i++) {
            printf("%05d %d %05d\n", nodes[i].address,\
                    nodes[i].key, nodes[i+1].address);
        }
        printf("%05d %d -1\n", nodes[i].address, nodes[i].key);
    } else {
        printf("0 -1\n");
    }

    return 0;
} 


发表于 2015-12-14 13:16:12 回复(0)