1097. Deduplication on a Linked List (25)

题目地址:http://www.patest.cn/contests/pat-a-practise/1097

主要是构造结构体 和 建立两个链表, 这里用到了map来表示绝对值是否存在,很方便的解决了问题,基本不用指针

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <unordered_map>
#include <algorithm>

using namespace std;

#define N 100001

int rootNum, n;

struct mydata{
  int address;
  int key;
  int nextaddr;
};

mydata v[N];

int main()
{
  //freopen("in", "r", stdin);
  int i;
  scanf("%d%d", &rootNum, &n);
  int tmpa, tmpkey, tmpnext;
  for (i = 0; i < n; i++)
  {
    scanf("%d%d%d", &tmpa, &tmpkey, &tmpnext);
    v[tmpa].address = tmpa;
    v[tmpa].key = tmpkey;
    v[tmpa].nextaddr = tmpnext;
  }

  vector<mydata> dt1;
  vector<mydata> dt2;
  unordered_map<int, int> um;
  int num = rootNum;
  while (num != -1)
  {
    int absKey = abs(v[num].key);
    if (um[absKey] == 0)
    {
      dt1.push_back(v[num]);
      um[absKey] = 1;
    }
    else{
      dt2.push_back(v[num]);
    }
    num = v[num].nextaddr;
  }
  int len1 = dt1.size();
  int len2 = dt2.size();
  printf("%05d %d", rootNum, dt1[0].key);
  for (i = 1; i < len1; i++)
  {
    printf(" %05d\n%05d %d", dt1[i].address, dt1[i].address, dt1[i].key);
  }
  printf(" -1\n");

  if (len2 == 1)
  {
    printf("%5d %d -1\n", dt2[0].address, dt2[0].key);
  }
  else if (len2 > 1)
  {
    printf("%05d %d", dt2[0].address, dt2[0].key);
    for (i = 1; i < len2; i++)
    {
      printf(" %05d\n%05d %d", dt2[i].address, dt2[i].address, dt2[i].key);
    }
    printf(" -1\n");
  }
  //printf("\n");
  return 0;
}

你可能感兴趣的:(1097. Deduplication on a Linked List (25))