1032 Sharing
题目链接
https://pintia.cn/problem-sets/994805342720868352/problems/994805460652113920
解题思路
一般思路
1.遍历两条链表,得到两个字符串s1,s2;
2.找出s1,s2的公共子序列长度 len;
3.根据len从尾节点遍历;
但这样比较麻烦,且得考虑空串情况;
优化思路
1.在输入介点时记录每个节点的状态为false;
2.遍历第一条链表,更改节点状态为true;
3.遍历第二条链表当遇到flag=true的节点时就是两条链表的公共后缀开始位置;
总结
1.cout补齐n位0:
cout<<setw(n)<<setfill('0')<<i<<endl;
2.cout输出数据时保留n位小数
cout<<fixed<<setprecision(n)<<i<<endl;
代码展示
#include<bits/stdc++.h>
using namespace std;
/*
思路:
*/
struct node{
int aft;
char c;
bool flag;
};
node ll[100000];
int main(){
int s1,s2,n;
cin>>s1>>s2>>n;
while(n--){
int a,b;char c;
cin>>a>>c>>b;
ll[a].aft=b;
ll[a].c=c;
ll[a].flag=false;
}
while(ll[s1].aft!=-1){
ll[s1].flag=true;
s1=ll[s1].aft;
}
for(int i=s2;i!=-1;i=ll[i].aft){
if(ll[i].flag){
// printf("%05d\n",i);
cout<<setw(5)<<setfill('0')<<i<<endl;
return 0;
}
}
printf("-1\n");
return 0;
}