赞
踩
1、统计难题 HDU - 1251
思路:
直接建一棵字典树,在建树的过程中,统计前缀出现的次数。那么我们就可以直接在查询时查到一个字符串的最后一个字符对应位置的sum值。
代码:
- #include<iostream>
- #include<algorithm>
- #define rep(i,a,b) for(int i=a;i<=b;i++)
- #define dep(i,a,b) for(int i=a;i>=b;i--)
- #define ll long long
- #include<string.h>
- #include<queue>
- #include<stack>
- #include<cstdio>
- #include<cmath>
- #include <stdlib.h>
- #include<stack>
- using namespace std;
- const int maxn=1000000+10;
- #define mod 1000000007
- #define INF 0x3f3f3f3f
- int dx[]= {-1,1,0,0};
- int dy[]= {0,0,-1,1};
- int n,k;
- char ch[20];
- int trie[maxn][30];
- int sum[maxn];
- int cnt;
- void inserts()
- {
- int s=0;
- for(int i=0;ch[i];i++)
- {
- int v=ch[i]-'a';
- if(trie[s][v]==0)
- {
- trie[s][v]=cnt++;
- }
- s=trie[s][v];
- sum[s]++;
- }
- }
- int finds()
- {
- int s=0;
- for(int i=0;ch[i];i++)
- {
- int v=ch[i]-'a';
- if(trie[s][v]==0)
- {
- return 0;
- }
- s=trie[s][v];
- }
- return sum[s];
- }
- int main()
- {
- cnt=1;
- while(gets(ch)&&ch[0]!=NULL)
- {
- inserts();
- }
- while(gets(ch))
- {
- int ans=finds();
- printf("%d\n",ans);
- }
- return 0;
- }

1、三数之和
https://leetcode-cn.com/problems/3sum/
2、四数之和
https://leetcode-cn.com/problems/4sum/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。