PAT 1032. Sharing

其实就是链表求交:

 1 #include <iostream>

 2 #include <cstdio>

 3 #include <cstdlib>

 4 #include <unordered_map>

 5 

 6 using namespace std;

 7 

 8 class Node {

 9 public:

10     Node() : data(0), next(0) {}

11     char data;

12     int next;

13 };

14 

15 void print_list(unordered_map<int, Node*>& mem, int head) {

16     int cur = head;

17     while (cur != -1) {

18         cout<<mem[cur]->data<<" ";

19         cur = mem[cur]->next;

20     }

21     cout<<endl;

22 };

23 

24 int step_list(unordered_map<int, Node*>& mem, int from, int n) {

25     if (n < 0) return -1;

26     int cur = from;

27     while (cur != -1) {

28         if (n == 0) {

29             break;

30         }

31         cur = mem[cur]->next;

32         n--;

33     }

34     return cur;

35 }

36 

37 int count_list(unordered_map<int, Node*>& mem, int from) {

38     if (from < 0) return 0;

39     int cur =  from;

40     int cnt = 0;

41     while (cur != -1) {

42         cur = mem[cur]->next;

43         cnt++;

44     }

45     return cnt;

46 }

47 

48 int main() {

49     int head_a, head_b;

50     int n;

51     

52     unordered_map<int, Node*> mem;

53     

54     cin>>head_a>>head_b>>n;

55     

56     for (int i=0; i<n; i++) {

57         int addr;

58         Node* np = new Node();

59         scanf("%d %c %d", &addr, &(np->data), &(np->next));

60         mem.insert(make_pair(addr, np));

61     }

62 

63     int cnt_a = count_list(mem, head_a);

64     int cnt_b = count_list(mem, head_b);

65     

66     int cnt_diff = cnt_a - cnt_b;

67     int head_long  = head_a;

68     int head_short = head_b;

69     if (cnt_diff < 0) {

70         cnt_diff = -cnt_diff;

71         head_long = head_b;

72         head_short= head_a;

73     }

74     

75     head_long = step_list(mem, head_long, cnt_diff);

76     

77     while (head_long != head_short) {

78         head_long = mem[head_long]->next;

79         head_short= mem[head_short]->next;

80     }

81     if (head_long < 0) {

82         printf("-1\n");

83     } else {

84         printf("%05d\n", head_long);

85     }

86     system("pause");

87     return 0;

88 }

 

你可能感兴趣的:(sha)