Codeforces Global Round 6 D - Decreasing Debts(思维)

Codeforces Global Round 6 D - Decreasing Debts(思维)_第1张图片
Codeforces Global Round 6 D - Decreasing Debts(思维)_第2张图片
题意:给定n个人,m个债务关系,要你简化一下债务关系使得债务总和最小。
思路:计算出每个人的盈or亏,分别放到两个数组里,然后随便乱连就行了。。。

#include 
using namespace std;
typedef long long ll;
struct node{
	int l,r;
	ll w;
};
const int maxn=2e5+1;
vector<int>v1,v2;
vector<node>ans;
ll d[maxn];
int main()
{
	int n,m;
	scanf("%d %d",&n,&m);
	while(m--)
	{
		ll u,v,w;
		scanf("%lld %lld %lld",&u,&v,&w);
		d[u]+=w;
		d[v]-=w;
	}
	for(int i=1;i<=n;++i)
	{
		if(d[i]>0) v1.push_back(i);
		if(d[i]<0) v2.push_back(i);
	}
	int l=0,r=0;
	while(l<v1.size()&&r<v2.size())
	{
		if(d[v1[l]]>abs(d[v2[r]]))
		d[v1[l]]+=d[v2[r]],ans.push_back({v1[l],v2[r],abs(d[v2[r]])}),r++;
		else if(d[v1[l]]<abs(d[v2[r]])) 
		d[v2[r]]+=d[v1[l]],ans.push_back({v1[l],v2[r],d[v1[l]]}),l++;
		else
		ans.push_back({v1[l],v2[r],d[v1[l]]}),l++,r++;
	}
	printf("%d\n",ans.size());
	for(int i=0;i<ans.size();++i) printf("%d %d %lld\n",ans[i].l,ans[i].r,ans[i].w);
}

你可能感兴趣的:(思维)