1032:Sharing

To find the first common node on the two link list;

// 题目1468:Sharing.cpp: 主项目文件。

//#include "stdafx.h"
#include <cstdio>
#include <algorithm>
using namespace std;

const int N=100003;

typedef struct Node
{
	int add,next;
}Node;
Node node[N];
Node list1[N],list2[N];
int n;

bool cmp(Node m1, Node m2)
{
	return m1.add<m2.add;
}

int findNext(int nextAdd, int start, int end)
{
	if(start>end)
		return -1;
	int mid=(start+end)/2;
	if(nextAdd==node[mid].add)
		return mid;
	else if(nextAdd>node[mid].add)
	{
		start=mid+1;
		return findNext(nextAdd, start, end);
	}
	else
	{
		end=mid-1;
		return findNext(nextAdd, start, end);
	}
}

int copy(int head,Node *list)
{
	int cur=findNext(head, 0, n-1);
	int length=0;
	while(cur!=-1)
	{
		list[length].add=node[cur].add;
		//list[length].ch=node[cur].ch;
		list[length++].next=node[cur].next;
		cur=findNext(node[cur].next, 0, n-1);
	}
	return length;
}

int sharing(int first, int second)
{
	int length1=copy(first,list1);
	int length2=copy(second,list2);
	int start1,start2,len;
	if(length1>length2)
		start1=length1-length2,start2=0,len=length2;
	else
		start2=length2-length1,start1=0,len=length1;
	for(int i=0;i<len;i++)
	{
		if(list1[start1+i].add==list2[start2+i].add)
			return list1[start1+i].add;
	}
	return -1;
}

int main()
{
    int first,second;
	char ch;
	while(scanf("%d%d%d",&first,&second,&n)==3)
	{
		for(int i=0;i<n;i++)
			scanf("%d%*c%c%d",&node[i].add,&ch,&node[i].next);
		sort(node,node+n,cmp);
		int res=sharing(first,second);
		if(res!=-1)
			printf("%05d\n",res);
		else
			printf("-1\n");
	}
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值