PAT甲级-1032 Sharing (25分)

题目:1032 Sharing (25分)
分析:找相同的后缀,代码1使用了set比较方便,代码2比较容易想到(第一次写的时候用了set,这次没想到┭┮﹏┭┮)
代码1:
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#define MAX 99999999
typedef long long ll;
using namespace std;
int n,m;
struct Node{

    int add;
    char data;
    int next;

};
Node node[100001];
int main()
{
    int s,d;
    scanf("%d%d%d",&s,&d,&n);
    for(int i = 0;i<n;i++)
    {
        int a,b;
        char x;
        scanf("%d %c%d",&a,&x,&b);
        node[a].add = a;
        node[a].data = x;
        node[a].next = b;
    }
    int t = 0;
    set<int>s1;
    while(s!=-1)
    {
        s1.insert(s);
        s = node[s].next;
    }
    while(d!=-1)
    {
        if(s1.find(d)!=s1.end())
        {
            printf("%05d",d);
            t = 1;
            break;
        }
        d = node[d].next;
    }
    if(!t)
        cout<<-1;
    return 0;
}
代码2:
#include <iostream>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#include<stack>
#include<algorithm>
#include<map>
#include<set>
#define MAX 99999999
using namespace std;
typedef long long ll;
struct node{
    char data;
    int add,next;
};
int main()
{
    node node[100010];
    int x,y,n;
    cin>>x>>y>>n;
    for(int i = 0;i<n;i++)
    {
        int a,b;
        char x;
        cin>>a>>x>>b;
        node[a].data = x;
        node[a].next = b;
    }
    int lena = 0;
    int lenb = 0;
    int a = x;
    int b = y;
    while(a != -1){
        lena ++;
        a = node[a].next;
    }
    while(b != -1){
        lenb ++;
        b = node[b].next;
    }
    int t ;
    if(lena >lenb){
        t = lena - lenb;
        while(t!=0){
            x = node[x].next;t--;
        }

    }
    else{
        t = lenb - lena;
        while(t!=0){
            y = node[y].next;t--;
        }

    }
    int f = 0;
    while(x != -1 && y != -1)
    {
        if(x == y){
            f = 1;
            break;
        }
        x = node[x].next;
        y = node[y].next;
    }
    if(f == 1)
        printf("%05d",x);
    else
        cout<<-1;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值