题目来源:
http://acm.hdu.edu.cn/showproblem.php?pid=4352
题目描述:
Problem Description
There are n houses in the village and some bidirectional roads connecting them. Every day peole always like to ask like this "How far is it if I want to go from house A to house B"? Usually it hard to answer. But luckily int this village the answer is always unique, since the roads are built in the way that there is a unique simple path("simple" means you can't visit a place twice) between every two houses. Yout task is to answer all these curious people.
Input
First line is a single integer T(T<=10), indicating the number of test cases.
For each test case,in the first line there are two numbers n(2<=n<=40000) and m (1<=m<=200),the number of houses and the number of queries. The following n-1 lines each consisting three numbers i,j,k, separated bu a single space, meaning that there is a road connecting house i and house j,with length k(0<k<=40000).The houses are labeled from 1 to n.
Next m lines each has distinct integers i and j, you areato answer the distance between house i and house j.
Output
For each test case,output m lines. Each line represents the answer of the query. Output a bland line after each test case.
Sample Input
2 3 2 1 2 10 3 1 15 1 2 2 3 2 2 1 2 100 1 2 2 1
Sample Output
10 25 100 100
Source
Recommend
lcy
解题思路:
题目大意是问一个区间里有多少个数,满足数字的LIS等于k,在longlong的范围内。首先考虑LIS怎么求,我们知道数字最多10,我们可以用一个1<<10的数来表示当前数的LIS,出现为1,例如123,那么就是1<<1+1<<2+1<<3,在求最长LIS用位运算代替nlog(n)算法,其中二进制1的出现次数就是LIS,用dp【25】【1<<10】【11】来表示,i表示当前位置,j表示现在LIS的状态,k表示LIS正好为k,剩下就是数位dp的基本操作了
代码:
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <queue>
#include <stack>
#include <cmath>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=1e5+10;
int t,k,sw[20];
ll a,b,dp[20][1<<10][11];
int getnum(int x)
{
int ans=0;
while(x)
{
if(x&1==1)ans++;
x>>=1;
}
return ans;
}
int update(int state,int i)
{
int j;
bool flag=0;
for(j=i;j<=9;j++)
if(state&(1<<j)){flag=1;break;}
int s=0;
if(flag)s=(state ^ (1<<j)) | (1<<i);
else s=state | (1<<i);
return s;
}
ll dfs(int pos,int state,bool lead,bool pd)//为什么要判断前导0
{
if(pos==-1)return getnum(state)==k;
if(!pd&&dp[pos][state][k]!=-1)return dp[pos][state][k];
int Max=pd?sw[pos]:9;
ll ans=0;
for(int i=0;i<=Max;i++)
{
int s=update(state,i);
ans+=dfs(pos-1,(lead&&i==0)?0:s,(lead&&i==0),(pd&&i==Max));
}
if(!pd)dp[pos][state][k]=ans;
return ans;
}
ll jj(ll x)
{
int cnt=0;
while(x)
{
sw[cnt++]=x%10;
x/=10;
}
return dfs(cnt-1,0,1,1);
}
int main()
{
int t,Case=0;
scanf("%d",&t);
memset(dp,-1,sizeof(dp));
while(t--)
{
scanf("%lld%lld%d",&a,&b,&k);
if(a==b)
printf("Case #%d: %d\n",++Case,0);
printf("Case #%d: %lld\n",++Case,jj(b)-jj(a-1));
}
return 0;
}