Spreadsheet(拓扑排序)

瞄了一眼题解才发现原来可以用拓扑排序来解决,并且在网上get到了很好的处理字符串的方法,注释掉的是二维数组储存法
,刚开始链式前向星一直过不去,改用二维数组(也ac了),后来修改后链式前向星没问题

#include<iostream>
#include<queue>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std; 
const int N = 1010;
int deg[N],ver[N],he[N],ne[N],a[N][N];
vector<vector<int> >s;
int tot,n,m;
void init()
{
	tot = 0;
	memset(deg,0,sizeof deg);
	memset(ver,0,sizeof ver);
	memset(he,0,sizeof he);
	memset(ne,0,sizeof ne);
	memset(a,0,sizeof a);
//	s = vector<vector<int> >(N,vector<int>(0,0));
}
void add(int a,int b)
{
	ver[++tot] = b,ne[tot] = he[a],he[a] = tot;
	deg[b]++;
}
void topsort()
{
	queue<int>q;
	for(int i=0;i<=n*m;i++)
	{
		if(deg[i]==0) q.push(i);
	}
	while(q.size())
	{
		int now = q.front(); q.pop();
		for(int i=he[now];i;i=ne[i])
		{
			int y = ver[i];
			a[y/m][y%m] += a[now/m][now%m];
//			cout<<now<<"->"<<y<<endl;
			if(--deg[y]==0) q.push(y);
		}
//		for(int i=0;i<s[now].size();i++)
//		{
//			int y = s[now][i];
//			a[y/m][y%m] += a[now/m][now%m];
//			cout<<now<<"->"<<y<<endl; 
//			if(--deg[y]==0) q.push(y);
//		}
	}
}
void deal(string ch,int x,int y)
{
	if(ch[0]>='0'&&ch[0]<='9')
	{
		int sum = 0;
		for(int i=0;i<ch.size();i++) sum = sum*10+ch[i]-'0';
		a[x][y] += sum;
		return ;
	}
	for(int i=1;i<ch.size();i++)
	{
		int dx = 0,dy = 0;
		for(;ch[i]!='+'&&i<ch.size();i++)
		{
			if(ch[i]>='A'&&ch[i]<='Z') dx = dx*26 + ch[i]-'A'+1;
			else dy = dy*10 + ch[i] - '0';
		}
		dy--;
		dx--;
		add(dy*m+dx,x*m+y);
//		s[dy*m+dx].push_back(x*m+y);
//		deg[x*m+y]++;
	}
}
int main()
{
	string ch;
	int t;
	cin>>t;
	while(t--)
	{
		init();
		cin>>m>>n;
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				cin>>ch;
				deal(ch,i,j);
			}
		}
		topsort();
		for(int i=0;i<n;i++)
		{
			cout<<a[i][0];
			for(int j=1;j<m;j++)
			{
				cout<<" "<<a[i][j];
			}
			cout<<endl;
		}
	}
}

发布了22 篇原创文章 · 获赞 3 · 访问量 638

猜你喜欢

转载自blog.csdn.net/qq_45520541/article/details/105052190