zoukankan      html  css  js  c++  java
  • [搜索]和为T

    简单dfs

    题目要求非常扯淡 按优先输出不包含n的, 其次n-1的

    所以dfs时记录路径, 按要求cmp sort

    时间31ms

    #include <bits/stdc++.h>
    using namespace std;
    const int MAXN = 1e5 + 7; 
    typedef long long ll;
    
    ll n, sum;
    ll arr[MAXN] = {0};
    
    struct node
    {
    	int brr[30], len;
    }ans[MAXN];
    
    ll pos = 0;
    
    bool cmp(node a, node b)
    {
    	ll x = 0, y = 0;
    
        for(int i = 0; i <= a.len; i++)
        {
            x = x + (1 << a.brr[i]);
        }
    
        for(int j = 0; j <= b.len; j++)
        {
            y = y + (1 << b.brr[j]);
        }
    
        return x < y;
    }
    
    void dfs(ll now, ll rsum, ll step)
    {
    	if(step > n)
    		return ; 
    	ans[pos].brr[step] = now;
    	
    	if(sum == rsum)
    	{
    		ans[pos].len = step;
    		++pos;
    		
    		for(int i = 0; i <= step; i++)
    			ans[pos].brr[i] = ans[pos - 1].brr[i];
    	}
    	
    	for(int i = now + 1; i < n; i++)
    	{
    		dfs(i, rsum + arr[i], step + 1);
    	}
    }
    
    int main()
    {
    	
    	cin>>n;
    	
    	for(int i = 0; i < n; i++)
    		cin>>arr[i];
    	
    	cin>>sum;
    	
    	for(int i = 0; i < n; i++)
    	{
    		dfs(i, arr[i], 0);	
    	}
    	
    	sort(ans, ans + pos, cmp);
    	
    	for(int i = 0; i < pos; i++)
    	{
    		for(int j = 0; j <= ans[i].len; j++)
    			cout<<arr[ ans[i].brr[j]]<<' ';
    		cout<<'
    ';
    	}	
    	
    	cout<<pos<<endl;
    	
    	return 0; 
    }
    
  • 相关阅读:
    正则表达式知识
    网页边上的弹窗
    表格的搜索
    表格的删除与添加
    添加标签和删除标签
    延迟提示框
    js知识
    反射的应用
    java反射知识
    事务的特性和隔离级别
  • 原文地址:https://www.cnblogs.com/zeolim/p/12270404.html
Copyright © 2011-2022 走看看