2021.08.05 P1738 洛谷的文件夹(树形结构)
P1738 洛谷的文件夹 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
重点:
1.树!!
题意:
给出n个网页路径,求1,2,…,i这i个路径中中有几个文件夹。
分析:
构造一棵树,类似于字典树,每次比较是否有这个文件夹,没有就加进去,有就沿着路经一直向下走。
代码如下:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
#include<map>
using namespace std;
const int N=50010;
int n,cnt;
struct node{
map<string,int>next;
}tree[N];
inline int read(){
int s=0,w=1;
char ch=getchar();
while(ch<'0'||ch>'9'){
if(ch=='-')w=-1;
ch=getchar();
}
while(ch<='9'&&ch>='0'){
s=s*10+ch-'0';
ch=getchar();
}
return s*w;
}
int main(){
n=read();
for(int i=1;i<=n;i++){
string s;
string tmp="";
int pos=0;
cin>>s;
for(int j=1;j<=s.length();j++){
if(s[j]=='/'||j==s.length()){
if(!tree[pos].next[tmp])tree[pos].next[tmp]=++cnt;
pos=tree[pos].next[tmp];
}else tmp=tmp+s[j];
}
cout<<cnt<<endl;
}
return 0;
}
posted on
浙公网安备 33010602011771号