pat1032 共享
我的思路是hash,然后双指针 上下每次各移动一个
一个不完善的代码,我开了一个10^6数组,devc艹觉得太大了,oj亦
#include<stdio.h>
#include <string>
const int N=100005;
int n,first,firstid;
using namespace std;
struct node
{
string data;int next;
} ;
node lnode[N];
void readin()
{
for(int i=0;i<n;i++)
{ int idtemp;scanf("%d",&idtemp);
scanf("%s %d",&lnode[idtemp].data,&lnode[idtemp].next);
}
}
//
//void readout()
//{ int temp=firstid;
//while(temp!=-1)
//{printf("%d %d %d\n",temp,lnode[temp].data,lnode[temp].next );temp=lnode[temp].next ;
//}
//}
void deletex(int pre)
{
lnode[pre].next=lnode[lnode[pre].next].next;
}
int main()
{
int firstid1,firstid2,cur1,cur2;
scanf("%d %d %d",&firstid1,&firstid2,&n);int tgt;
readin();
cur1=firstid1;cur2=firstid2;
bool hs[N]={0};
bool flag=0;
int ans=-1;;
while(lnode[cur1].next !=-1 || lnode[cur2].next!=-1)
{
if(!hs[cur1])hs[cur1]=1;
else
{ans = cur1;flag=1;break;
}
if(!hs[cur2])hs[cur2]=1;
else
{ans = cur2;flag=1;break;
}
//后移
if(lnode[cur1].next !=-1 )cur1=lnode[cur1].next;
if(lnode[cur2].next !=-1 )cur2=lnode[cur2].next;
}
printf("%d",ans);
}
c艹倒是可以输出答案,但会输出后栈溢出
oj过不了,说运行时错误
参考昨天小网站哪位大佬,它没有用链表,或者说,没有用结构体,而是用了两个数组,分别存放data和next
参考后我的ac、代码,注意格式化输出%05d
#include<stdio.h>
#include<bits/stdc++.h>
#include <string>
const int N=100005;
int n,first,firstid;
using namespace std;
string tp="";
struct node
{
char data;int next;
} ;
//node lnode[N];
int lnxt[N];
char c[N];
void readin()
{
for(int i=0;i<n;i++)
{
// printf("%d/%d\n",i,n);
int idtemp;
char w;int valuetemp;
scanf("%d %c %d",&idtemp,&w,&valuetemp);
// scanf("%c %d",&w,&valuetemp);先%d,再%c %d分次输入似乎会跳跃,不行
c[idtemp]=w;lnxt[idtemp]=valuetemp;
// printf("--%d/%d\n",i,n);
}
}
//
//void readout()
//{ int temp=firstid;
//while(temp!=-1)
//{printf("%d %d %d\n",temp,lnode[temp].data,lnode[temp].next );temp=lnode[temp].next ;
//}
//}
//void deletex(int pre)
//{
// lnode[pre].next=lnode[lnode[pre].next].next;
//}
int main()
{
int firstid1,firstid2,cur1,cur2;
scanf("%d %d %d",&firstid1,&firstid2,&n);
readin();
cur1=firstid1;cur2=firstid2;
bool hs[N]={0};
bool flag=0;
int ans=-1;;
while(cur1 !=-1)
{
hs[cur1]=1; cur1=lnxt[cur1];
}
while(cur2!=-1)
{
if(hs[cur2])
{ans = cur2;flag=1;break;
}
//后移
cur2=lnxt[cur2];
}
if(ans>0)printf("%05d",ans);else printf("-1");
}
大佬的
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 100010;
int ne[N], h1, h2, n;
char e[N];
bool st[N];
int main()
{
scanf("%d %d %d", &h1, &h2, &n);
for (int i = 0; i < n; i ++ )
{
int add, next;
char w;
scanf("%d %c %d", &add, &w, &next);
e[add] = w, ne[add] = next;
}
for (int i = h1; ~i; i = ne[i])
st[i] = true;
for (int i = h2; ~i; i = ne[i])
if(st[i])
{
printf("%05d", i);
return 0;
}
cout << -1 << endl;
return 0;
}