1032. Sharing (25)

题目地址:http://www.patest.cn/contests/pat-a-practise/1032
链表考研真题

/* 1032. Sharing (25) http://www.patest.cn/contests/pat-a-practise/1032 利用deque 很容易实现 不过采用链表LNode的实现差不多也类似,写起来麻烦点 */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <string>
#include <unordered_map>
#include <queue>
#include <algorithm>
#include <iostream>
using namespace std;

#define N 100005

int addr1 , addr2 , n ;

struct data{
    int addr ;
    char da ; 
    int nextaddr;
};

data tdata[N];

int main()
{
    //freopen("in.txt","r",stdin);
    scanf("%d%d%d",&addr1,&addr2,&n);
    int i , j ;
    int a1,a2;
    char c;
    for(i = 0 ; i < n ; i ++)
    {
        scanf("%d %c %d",&a1,&c,&a2);
        tdata[a1].addr = a1;
        tdata[a1].da = c;
        tdata[a1].nextaddr = a2;
    }
    deque<data> vd1,vd2;
    int t = addr1;
    while(t != -1)
    {
        vd1.push_back(tdata[t]);
        t = tdata[t].nextaddr;
    }
    t = addr2;
    while(t != -1)
    {
        vd2.push_back(tdata[t]);
        t = tdata[t].nextaddr;
    }
    int ans = -1 ;
    while(!vd1.empty() && !vd2.empty())
    {
        data d1 = vd1.back() ;
        data d2 = vd2.back() ;
        if(d1.da == d2.da && d1.addr == d2.addr && d1.nextaddr == d2.nextaddr)
        {
            ans = d1.addr;
            vd1.pop_back();
            vd2.pop_back();
        }else{
            break;
        }
    }
    if(ans == -1)
        printf("-1");
    else
        printf("%05d\n",ans);
    return 0;
}

你可能感兴趣的:(1032. Sharing (25))